diff --git a/plugins/TestingList.java b/plugins/TestingList.java index 9866aa6..706faa7 100644 --- a/plugins/TestingList.java +++ b/plugins/TestingList.java @@ -3,9 +3,8 @@ */ // -import ch.psi.pshell.core.Controller; -import ch.psi.utils.swing.MonitoredPanel; import ch.psi.pshell.ui.Panel; +import ch.psi.pshell.ui.Plugin; import ch.psi.utils.swing.SwingUtils; import ch.psi.wsaf.Task; import java.io.File; @@ -25,6 +24,8 @@ import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; +import java.nio.file.Path; +import java.nio.file.Paths; import java.util.ArrayList; import java.util.Iterator; import java.util.List; @@ -49,8 +50,6 @@ import static org.python.bouncycastle.util.Arrays.append; */ public class TestingList extends Panel { - NetbeansPluginPanel testingList; - Task task = new Task() { @Override protected Object execute() throws Exception { @@ -58,24 +57,20 @@ public class TestingList extends Panel { } }; - /** - * - * @return jPanel - */ - @Override - protected JPanel create() { - try { - testingList = new NetbeansPluginPanel(); - - } catch (IOException ex) { - Logger.getLogger(TestingList.class.getName()).log(Level.SEVERE, null, ex); + public TestingList() throws Exception{ + initComponents(); + initLogger(); + buildTable(); + try{ + loadTests(); + } catch (Exception ex){ + getLogger().severe(ex.getMessage()); } - return testingList; } //delete this @Override - protected void onExecutedFile(String fileName, Object result) { + public void onExecutedFile(String fileName, Object result) { int iCurrentTestPos = 0; try { Object ret = eval("ret"); @@ -85,33 +80,33 @@ public class TestingList extends Panel { System.out.println("onExecutedFile: received end of test for test " + fileName); // if (ret != "") { //start next test - if (testingList.isTestRunAllowed() && testingList.runningTestsCount() == 0) { - // testingList.executeTests(iCurrentTestPos); + if (isTestRunAllowed() && runningTestsCount() == 0) { + // executeTests(iCurrentTestPos); } /* } else { // ret empty means that either the test script does not have variable ret, or that the script could not be started at all ret = "Could not start test script or script doea not contain default variables"; sStatus = TestStatus.FAILURE.toString(); - String[] dsDeviceName = testingList.getTestInProgress(); - //SwingUtils.showException(getComponent(), ex ); + String[] dsDeviceName = getTestInProgress(); + //SwingUtils.showException(this, ex ); if (dsDeviceName[0] != "") { - iCurrentTestPos = testingList.showResult(dsDeviceName[0], fileName, ret.toString(), sStatus); + iCurrentTestPos = showResult(dsDeviceName[0], fileName, ret.toString(), sStatus); //start next test - if (testingList.isTestRunAllowed() && testingList.runningTestsCount()==0) { - testingList.executeTest(iCurrentTestPos); + if (isTestRunAllowed() && runningTestsCount()==0) { + executeTest(iCurrentTestPos); } } } */ } catch (Exception ex) { String ret = "Could not start test script"; String sStatus = TestStatus.FAILURE.toString(); - String[] dsDeviceName = testingList.getTestInProgress(); - //SwingUtils.showException(getComponent(), ex ); - SwingUtils.showMessage(getComponent(), "onExecutedFile()", ex.toString() + " " + dsDeviceName[0]); + String[] dsDeviceName = getTestInProgress(); + //SwingUtils.showException(this, ex ); + SwingUtils.showMessage(this, "onExecutedFile()", ex.toString() + " " + dsDeviceName[0]); if (dsDeviceName[0] != "") { - iCurrentTestPos = testingList.showResult(dsDeviceName[0], fileName, ret, sStatus); + iCurrentTestPos = showResult(dsDeviceName[0], fileName, ret, sStatus); //start next test - if (testingList.isTestRunAllowed()) { - // testingList.executeTests(iCurrentTestPos + 1); + if (isTestRunAllowed()) { + // executeTests(iCurrentTestPos + 1); } } } @@ -213,7 +208,7 @@ public class TestingList extends Panel { /** * - * @return + * @return ImageIcon corresponding to the selected testStatus */ public ImageIcon Icon() { String iconFileName = this.IconFilename(); @@ -226,21 +221,22 @@ public class TestingList extends Panel { }; /** - * + * Sequence options: AFTER: the test starts after the test above has + * finished TOGETHER: the test starts at the same time as the test above */ public enum StartSequence { - START_SEQ_AFTER, - START_SEQ_TOGETHER; + AFTER, + TOGETHER; @Override public final String toString() { String status = ""; switch (this) { - case START_SEQ_AFTER: + case AFTER: status = "After previous"; break; - case START_SEQ_TOGETHER: + case TOGETHER: status = "With previous"; break; } @@ -249,47 +245,83 @@ public class TestingList extends Panel { }; /** - * + * List of Keys defining the arguments to be passed to a test script */ - public class NetbeansPluginPanel extends MonitoredPanel { + public enum testArgNames { - Logger logger = Logger.getLogger("TestsLog"); - //these paths are converted to unix or win path according to host OS - private final String TESTS_DEVICES_DEFAULT_DIR = new java.io.File(".").getCanonicalPath() - + FilenameUtils.separatorsToSystem("/home/script/tests/devices/"); - private final String TESTS_TESTS_DEFAULT_DIR = new java.io.File(".").getCanonicalPath() - + FilenameUtils.separatorsToSystem("/home/script/tests/tests/"); - private final String TESTS_LOG_DEFAULT_DIR = new java.io.File(".").getCanonicalPath() - + FilenameUtils.separatorsToSystem("/home/script/tests/log/TestsLog" + getnow() + ".txt"); + PARAMETERS, + TEST, + DEVICE, + TEST_PATH, + STATUS; - private void initLogger() { - try { - FileHandler fh; - // This block configure the logger with handler and formatter - fh = new FileHandler(TESTS_LOG_DEFAULT_DIR); - logger.addHandler(fh); - SimpleFormatter formatter = new SimpleFormatter(); - fh.setFormatter(formatter); - logger.log(Level.INFO, "New testing session"); - } catch (SecurityException e) { - SwingUtils.showMessage(this, "initLogger()", e.toString()); - } catch (IOException e) { - SwingUtils.showMessage(this, "initLogger()", e.toString()); + @Override + public final String toString() { + String status = ""; + switch (this) { + case PARAMETERS: + status = "parameters"; + break; + case TEST: + status = "test"; + break; + case DEVICE: + status = "device"; + break; + case TEST_PATH: + status = "testPath"; + break; + case STATUS: + status = "status"; + break; } + return status; } + }; - /** - * - * @throws IOException - */ - public NetbeansPluginPanel() throws IOException { - initComponents(); - initLogger(); - buildTable(); - loadTests(); + Logger logger = Logger.getLogger("TestsLog"); + //these paths are converted to unix or win path according to host OS + // private final String TESTS_DEVICES_DEFAULT_DIR = new java.io.File(".").getCanonicalPath() + // + FilenameUtils.separatorsToSystem("/home/script/tests/devices/"); + // private final String TESTS_TESTS_DEFAULT_DIR = new java.io.File(".").getCanonicalPath() + // + FilenameUtils.separatorsToSystem("/home/script/tests/tests/"); + // private final String TESTS_LOG_DEFAULT_DIR = new java.io.File(".").getCanonicalPath() + // + FilenameUtils.separatorsToSystem("/home/script/tests/log/TestsLog" + getnow() + ".txt"); + + private final Path TESTS_DEVICES_DEFAULT_DIR = Paths.get(".","home", "script", "tests", "devices"); + private final Path TESTS_TESTS_DEFAULT_DIR = Paths.get(".","home", "script", "tests", "tests"); + private final Path TESTS_LOG_DEFAULT_DIR = Paths.get(".","home", "script", "tests", "log", "TestsLog"+ getnow() + ".txt"); + + + private void log(Object text){ + try { + getController().getDataManager().appendLog(String.valueOf(text)); + } catch (IOException ex) { + Logger.getLogger(TestingList.class.getName()).log(Level.SEVERE, null, ex); } + } + private void initLogger() { + try { + + FileHandler fh; + // This block configure the logger with handler and formatter + fh = new FileHandler(TESTS_LOG_DEFAULT_DIR.toString()); + logger.addHandler(fh); + SimpleFormatter formatter = new SimpleFormatter(); + fh.setFormatter(formatter); + log("INFO - " + "New testing session"); + } catch (SecurityException e) { + SwingUtils.showMessage(this, "initLogger()", e.toString()); + } catch (IOException e) { + SwingUtils.showMessage(this, "initLogger()", e.toString()); + } + } - @SuppressWarnings("unchecked") + /** + * + * @throws IOException + */ + @SuppressWarnings("unchecked") // //GEN-BEGIN:initComponents private void initComponents() { @@ -452,19 +484,19 @@ public class TestingList extends Panel { } }//GEN-LAST:event_jButtonRunActionPerformed - private void setButtonToStop() { - abort(); - this.jButtonRun.setToolTipText("Run selected tests"); - jButtonRun.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/play-circled-64-000000.png"))); - this.jTable1.setEnabled(true); - } + private void setButtonToStop() { + abort(); + this.jButtonRun.setToolTipText("Run selected tests"); + jButtonRun.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/play-circled-64-000000.png"))); + this.jTable1.setEnabled(true); + } - private void setButtonToStart() { - this.jButtonRun.setToolTipText("Stop tests"); - jButtonRun.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/stop-circled-64-000000.png"))); - this.jTable1.clearSelection(); - this.jTable1.setEnabled(false); - } + private void setButtonToStart() { + this.jButtonRun.setToolTipText("Stop tests"); + jButtonRun.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/stop-circled-64-000000.png"))); + this.jTable1.clearSelection(); + this.jTable1.setEnabled(false); + } private void jCheckBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBox1ActionPerformed boolean bSelected = jCheckBox1.isSelected(); @@ -491,22 +523,19 @@ public class TestingList extends Panel { try { switch (evt.getClickCount()) { case 1: - int colIndex = jTable1.getSelectedColumn(); - if (colIndex == COL.CHECK.ordinal()) { - updateStatus(); - } break; case 2: openDetails(); break; } + updateStatus(); } catch (Exception ex) { SwingUtils.showException(this, ex); } } }//GEN-LAST:event_jTable1MouseClicked - //oopen the log file using one of th default OS text reades + //oopen the log file using one of th default OS text reades private void jButtonOpenLogActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonOpenLogActionPerformed String cmd; if (System.getProperty("os.name").toLowerCase().contains("windows")) { @@ -524,10 +553,7 @@ public class TestingList extends Panel { }//GEN-LAST:event_jButtonOpenLogActionPerformed private void jTable1KeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTable1KeyReleased - int colIndex = jTable1.getSelectedColumn(); - if (colIndex == COL.CHECK.ordinal()) { - updateStatus(); - } + updateStatus(); }//GEN-LAST:event_jTable1KeyReleased private void jButtonMoveDownActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonMoveDownActionPerformed @@ -545,7 +571,7 @@ public class TestingList extends Panel { //Object ret = eval("parallelize((run,('testLocalVar1',globals(),{'a':'21', 'b':34})), (run,('testLocalVar2',globals(),{'a':231, 'b':234})))"); Object ret; ret = eval("parallelize((run,('dummy',)))"); - ret = eval("parallelize((run,('testLocalVar1',{'a':21, 'b':34})), (run,('testLocalVar2', {'a':231, 'b':234})))"); + ret = eval("parallelize((run,('testLocalVar1', None,{'a':21, 'b':34})), (run,('testLocalVar2', None, {'a':231, 'b':234})))"); Object ret1 = ((ArrayList) ret).get(0); Object ret2 = ((ArrayList) ret).get(1); System.out.println(String.valueOf(ret1)); @@ -578,752 +604,801 @@ public class TestingList extends Panel { // End of variables declaration//GEN-END:variables // - /** - *returns whether or not the tests can run - * (Run launched by the user) - * - * @return status of run button. True = tests launching sequence is running - */ - public boolean isTestRunAllowed() { - return (this.jButtonRun.getToolTipText().equals("Stop tests") && pendingTestsCount() > 0); - } + /** + * returns whether or not the tests can run (Run launched by the user) + * + * @return status of run button. True = tests launching sequence is running + */ + public boolean isTestRunAllowed() { + return (this.jButtonRun.getToolTipText().equals("Stop tests") && pendingTestsCount() > 0); + } - /** - * move selected rows up in table - */ - private void moveUp() { - DefaultTableModel model = (DefaultTableModel) jTable1.getModel(); - int[] rows = jTable1.getSelectedRows(); - if (rows[0] - 1 >= 0) { - jTable1.setAutoCreateRowSorter(false); - model.moveRow(rows[0], rows[rows.length - 1], rows[0] - 1); - jTable1.setAutoCreateRowSorter(true); - jTable1.setRowSelectionInterval(rows[0] - 1, rows[rows.length - 1] - 1); + /** + * move selected rows up in table + */ + private void moveUp() { + DefaultTableModel model = (DefaultTableModel) jTable1.getModel(); + int[] rows = jTable1.getSelectedRows(); + if (rows[0] - 1 >= 0) { + jTable1.setAutoCreateRowSorter(false); + model.moveRow(rows[0], rows[rows.length - 1], rows[0] - 1); + jTable1.setAutoCreateRowSorter(true); + jTable1.setRowSelectionInterval(rows[0] - 1, rows[rows.length - 1] - 1); + } + } + + /** + * move selected rows down in table + */ + private void moveDown() { + DefaultTableModel model = (DefaultTableModel) jTable1.getModel(); + int[] rows = jTable1.getSelectedRows(); + if (rows[rows.length - 1] < jTable1.getRowCount()) { + jTable1.setAutoCreateRowSorter(false); + model.moveRow(rows[0], rows[rows.length - 1], rows[0] + 1); + jTable1.setAutoCreateRowSorter(true); + jTable1.setRowSelectionInterval(rows[0] + 1, rows[rows.length - 1] + 1); + } + } + + /** + * open details of the selected row in a new panel + * + * @throws exception + */ + private void openDetails() throws Exception { + //pick details from the clicked row + int row = jTable1.getSelectedRow(); + String sDeviceName = jTable1.getValueAt(row, COL.DEVICENAME.ordinal()).toString(); + String sTestName = jTable1.getValueAt(row, COL.TESTNAME.ordinal()).toString(); + String sTestPath = String.valueOf(jTable1.getValueAt(row, COL.TESTPATH.ordinal())); + String sTestCaseName = jTable1.getValueAt(row, COL.TESTSUITE.ordinal()).toString(); + String sTestDescription = jTable1.getValueAt(row, COL.TESTDESCR.ordinal()).toString(); + String sDeviceDescription = jTable1.getValueAt(row, COL.DEVICEDESCR.ordinal()).toString(); + String sLastResult = jTable1.getValueAt(row, COL.RESULT.ordinal()).toString(); + String sResultTime = jTable1.getValueAt(row, COL.TIME.ordinal()).toString(); + String sTestHelp = String.valueOf(jTable1.getValueAt(row, COL.TESTHELP.ordinal())); + HashMap mParameters = buildParametersMap(String.valueOf(jTable1.getValueAt(row, COL.TESTPARAMS.ordinal()))); + //create map for passing details to Details Panel + HashMap details = new HashMap(); + details.put("deviceName", sDeviceName); + details.put("deviceDescription", sDeviceDescription); + details.put("testDescription", sTestDescription); + details.put("testSuite", sTestCaseName); + details.put("testName", sTestName); + details.put("testResult", sLastResult); + details.put("time", sResultTime); + details.put("parameters", mParameters); + details.put("testHelp", sTestHelp); + details.put("testPath", sTestPath); + //open details panel + JDialog dlg = new JDialog(getView(), "Test Details - " + sTestName, true); + //create a class to visualise the details panel + Class testingListDetailsClass = getController().getClassByName("TestingListDetails"); + JPanel detailsPanel = (JPanel) testingListDetailsClass.getConstructor(new Class[]{HashMap.class}).newInstance(new Object[]{details}); + + dlg.getContentPane().add(detailsPanel); + //dlg.add(new TestingListDetails()); + dlg.pack(); + dlg.setVisible(true); + } + + /** + * put the test result in table + * + * @param deviceName name of the device to search in table + * @param testPath path of the test to search in table + * @param res String result returned by the test + * @param status String status returned by the test + * @return int index of the row of the device in table + */ + public int showResult(String deviceName, String testPath, String res, String status) { + int rowD = -1; + String sTestName = testPath; + //getController().getDataManager().appendLog(str(log)); + + getLogger().log(Level.FINE, "Looking for: deviceName: " + deviceName + "; testPath: " + testPath + " in table."); + String sStatus; + if (status == "true") { + sStatus = TestStatus.SUCCESS.toString(); + } else if (status == "false") { + sStatus = TestStatus.FAILURE.toString(); + } else { + sStatus = status; + } + //search for device name in table + for (int row = 0; row <= jTable1.getRowCount() - 1; row++) { + if (deviceName.equals(jTable1.getValueAt(row, COL.DEVICENAME.ordinal())) + && testPath.equals(jTable1.getValueAt(row, COL.TESTPATH.ordinal()))) { + rowD = row; + sTestName = jTable1.getValueAt(rowD, COL.TESTNAME.ordinal()).toString(); + break; } } + ImageIcon icon = new ImageIcon(); + switch (sStatus) { + case "Success": + icon = TestStatus.SUCCESS.Icon(); + logger.log(Level.INFO, sStatus + " - Device: " + deviceName + "; Test: " + sTestName + "; Result: " + res); + log("INFO - " + sStatus + " - Device: " + deviceName + "; Test: " + sTestName + "; Result: " + res); + break; + case "Failure": + icon = TestStatus.FAILURE.Icon(); + logger.log(Level.SEVERE, sStatus + " - Device: " + deviceName + "; Test: " + sTestName + "; Result: " + res); + break; + case "Running": + icon = TestStatus.RUNNING.Icon(); + //logger.log(Level.INFO, "Running Test: " + sTestName + "."); + break; + } + if (rowD >= 0) { + jTable1.setValueAt(icon, rowD, COL.ICON.ordinal()); + jTable1.setValueAt(getNow(), rowD, COL.TIME.ordinal()); + jTable1.setValueAt(res, rowD, COL.RESULT.ordinal()); + jTable1.setValueAt(sStatus, rowD, COL.STATUS.ordinal()); + } else { + logger.log(Level.SEVERE, "Cant find Test: " + testPath + " in table."); + } + //check if there are still pending tests. If not, set the status of the tool to Stopped. + if (pendingTestsCount() == 0 && runningTestsCount() == 0) { + setToStopped(); + } + return rowD; + } - /** - * move selected rows down in table - */ - private void moveDown() { - DefaultTableModel model = (DefaultTableModel) jTable1.getModel(); - int[] rows = jTable1.getSelectedRows(); - if (rows[rows.length - 1] < jTable1.getRowCount()) { - jTable1.setAutoCreateRowSorter(false); - model.moveRow(rows[0], rows[rows.length - 1], rows[0] + 1); - jTable1.setAutoCreateRowSorter(true); - jTable1.setRowSelectionInterval(rows[0] + 1, rows[rows.length - 1] + 1); + /** + * returns the amount of tests currently in Pending state + * + * @return int counter of pending tests + */ + public int pendingTestsCount() { + return testsStatusCount(TestStatus.PENDING); + } + + /** + * returns the amount of tests currently in Running state + * + * @return int counter of running tests + */ + public int runningTestsCount() { + return testsStatusCount(TestStatus.RUNNING); + } + + /** + * returns the amount of tests currently in Pending state + * + * @return int counter of successful tests + */ + public int successTestsCount() { + return testsStatusCount(TestStatus.SUCCESS); + } + + /** + * returns the amount of tests currently in "status" state + * + * @param status type of status to count + * @return int counter with occurrences of the status + */ + private int testsStatusCount(TestStatus status) { + String sStatus; + boolean bSelected; + int iPendingTestsCount = 0; + for (int row = 0; row < jTable1.getRowCount(); row++) { + bSelected = (boolean) jTable1.getValueAt(row, COL.CHECK.ordinal()); + sStatus = jTable1.getValueAt(row, COL.STATUS.ordinal()).toString(); + if (bSelected && sStatus == status.toString()) { + iPendingTestsCount++; } } + return iPendingTestsCount; + } - /** - * open details of the selected row in a new panel - * - * @throws exception - */ - private void openDetails() throws Exception { - //pick details from the clicked row - int row = jTable1.getSelectedRow(); - String sDeviceName = jTable1.getValueAt(row, COL.DEVICENAME.ordinal()).toString(); - String sTestName = jTable1.getValueAt(row, COL.TESTNAME.ordinal()).toString(); - String sTestPath = String.valueOf(jTable1.getValueAt(row, COL.TESTPATH.ordinal())); - String sTestCaseName = jTable1.getValueAt(row, COL.TESTSUITE.ordinal()).toString(); - String sTestDescription = jTable1.getValueAt(row, COL.TESTDESCR.ordinal()).toString(); - String sDeviceDescription = jTable1.getValueAt(row, COL.DEVICEDESCR.ordinal()).toString(); - String sLastResult = jTable1.getValueAt(row, COL.RESULT.ordinal()).toString(); - String sResultTime = jTable1.getValueAt(row, COL.TIME.ordinal()).toString(); - String sTestHelp = String.valueOf(jTable1.getValueAt(row, COL.TESTHELP.ordinal())); - HashMap mParameters = buildParametersMap(String.valueOf(jTable1.getValueAt(row, COL.TESTPARAMS.ordinal()))); - //create map for passing details to Details Panel - HashMap details = new HashMap(); - details.put("deviceName", sDeviceName); - details.put("deviceDescription", sDeviceDescription); - details.put("testDescription", sTestDescription); - details.put("testSuite", sTestCaseName); - details.put("testName", sTestName); - details.put("testResult", sLastResult); - details.put("time", sResultTime); - details.put("parameters", mParameters); - details.put("testHelp", sTestHelp); - details.put("testPath", sTestPath); - //open details panel - JDialog dlg = new JDialog(getView(), "Test Details - " + sTestName, true); - //create a class to visualise the details panel - Class testingListDetailsClass = getController().getClassByName("TestingListDetails"); - JPanel detailsPanel = (JPanel) testingListDetailsClass.getConstructor(new Class[]{HashMap.class}).newInstance(new Object[]{details}); + /** + * set the tests to stopped + */ + private void setToStopped() { + //No more tests to play. Stop + setButtonToStop(); + logger.log(Level.INFO, "End of tests."); + } - dlg.getContentPane().add(detailsPanel); - //dlg.add(new TestingListDetails()); - dlg.pack(); - dlg.setVisible(true); - } - - /** - * put the test result in table - * - * @param deviceName name of the device to search in table - * @param testPath path of the test to search in table - * @param res String result returned by the test - * @param status String status returned by the test - * @return int index of the row of the device in table - */ - public int showResult(String deviceName, String testPath, String res, String status) { - int rowD = -1; - String sTestName = testPath; - logger.log(Level.FINE, "Looking for: deviceName: " + deviceName + "; testPath: " + testPath + " in table."); - String sStatus; - if (status == "true") { - sStatus = TestStatus.SUCCESS.toString(); - } else if (status == "false") { - sStatus = TestStatus.FAILURE.toString(); - } else { - sStatus = status; - } - //search for device name in table + /** + * get the first test currently in progress + * + * @return properties of the test in progress + */ + public String[] getTestInProgress() { + String[] dsTestProperties = {"", ""}; + //search for device name in table + try { for (int row = 0; row <= jTable1.getRowCount() - 1; row++) { - if (deviceName.equals(jTable1.getValueAt(row, COL.DEVICENAME.ordinal())) - && testPath.equals(jTable1.getValueAt(row, COL.TESTPATH.ordinal()))) { - rowD = row; - sTestName = jTable1.getValueAt(rowD, COL.TESTNAME.ordinal()).toString(); + if (jTable1.getValueAt(row, COL.STATUS.ordinal()).toString().equals(TestStatus.RUNNING.toString())) { + dsTestProperties[0] = jTable1.getValueAt(row, COL.DEVICENAME.ordinal()).toString(); + dsTestProperties[1] = jTable1.getValueAt(row, COL.TESTPATH.ordinal()).toString(); break; } } - ImageIcon icon = new ImageIcon(); - switch (sStatus) { - case "Success": - icon = TestStatus.SUCCESS.Icon(); - logger.log(Level.INFO, sStatus + " - Device: " + deviceName + "; Test: " + sTestName + "; Result: " + res); - break; - case "Failure": - icon = TestStatus.FAILURE.Icon(); - logger.log(Level.SEVERE, sStatus + " - Device: " + deviceName + "; Test: " + sTestName + "; Result: " + res); - break; - case "Running": - icon = TestStatus.RUNNING.Icon(); - //logger.log(Level.INFO, "Running Test: " + sTestName + "."); - break; + } catch (Exception ex) { + this.setToStopped(); + SwingUtils.showMessage(this, "getTestInProgress()", ex.toString()); + } finally { + return dsTestProperties; + } + } + + /** + * returns the status of the specified test name for specified device name + * + * @param deviceName name of the device + * @param testPath path of the test file + * @return String containing the result returned by the test + */ + public String getResult(String deviceName, String testPath) { + String sStatus = ""; + int rowD = -1, colT = -1; + //search for device name in table + for (int row = 0; row <= jTable1.getRowCount() - 1; row++) { + if (deviceName.equals(jTable1.getValueAt(row, COL.DEVICENAME.ordinal()))) { + rowD = row; + break; } - if (rowD >= 0) { - jTable1.setValueAt(icon, rowD, COL.ICON.ordinal()); - jTable1.setValueAt(getNow(), rowD, COL.TIME.ordinal()); - jTable1.setValueAt(res, rowD, COL.RESULT.ordinal()); - jTable1.setValueAt(sStatus, rowD, COL.STATUS.ordinal()); + } + if (rowD >= 0) { + //search for test in table + if (testPath.equals(jTable1.getValueAt(rowD, COL.TESTPATH.ordinal()))) { + colT = COL.TESTNAME.ordinal(); + } + } + //get the test result + if (colT >= 0 && rowD >= 0) { + sStatus = jTable1.getValueAt(rowD, COL.STATUS.ordinal()).toString(); + } + return sStatus; + } + + /** + * visualise test status (columns status and icon) + */ + public void updateStatus() { + String sStatus; + boolean bSelected; + ImageIcon icon = null; + String sStart; + for (int row = 0; row <= jTable1.getRowCount() - 1; row++) { + bSelected = (boolean) jTable1.getValueAt(row, COL.CHECK.ordinal()); + sStart = String.valueOf(jTable1.getValueAt(row, COL.STARTSEQUENCE.ordinal())); + if (bSelected) { + sStatus = TestStatus.PENDING.toString(); + icon = TestStatus.PENDING.Icon(); + if (sStart == "") { + sStart = StartSequence.AFTER.toString(); + } } else { - logger.log(Level.SEVERE, "Cant find Test: " + testPath + " in table."); + sStatus = TestStatus.DISABLED.toString(); + icon = TestStatus.DISABLED.Icon(); + sStart = ""; } - //check if there are still pending tests. If not, set the status of the tool to Stopped. - if (pendingTestsCount() == 0 && runningTestsCount() == 0) { - setToStopped(); - } - return rowD; + jTable1.setValueAt(bSelected, row, COL.CHECK.ordinal()); + jTable1.setValueAt(icon, row, COL.ICON.ordinal()); + jTable1.setValueAt(sStatus, row, COL.STATUS.ordinal()); + jTable1.setValueAt(sStart, row, COL.STARTSEQUENCE.ordinal()); } + } - - /** - *returns the amount of tests currently in Pending state - * - * @return int counter of pending tests - */ - public int pendingTestsCount() { - return testsStatusCount(TestStatus.PENDING); - } + /** + * launch the execution of the tests + */ + public void executeTests() { + RunTest runTest = new RunTest(); + Thread t = new Thread(runTest); + t.start(); + } - - /** - *returns the amount of tests currently in Running state - * - * @return int counter of running tests - */ - public int runningTestsCount() { - return testsStatusCount(TestStatus.RUNNING); - } + /** + * + */ + public class RunTest implements Runnable { - - /** - *returns the amount of tests currently in Pending state - * - * @return int counter of successful tests - */ - public int successTestsCount() { - return testsStatusCount(TestStatus.SUCCESS); - } + private HashMap mParameters; + //private HashMap args; + private HashMap hTests; /** - * returns the amount of tests currently in "status" state - * - * @param status type of status to count - * @return int counter with occurrences of the status - */ - private int testsStatusCount(TestStatus status) { - String sStatus; - boolean bSelected; - int iPendingTestsCount = 0; - for (int row = 0; row < jTable1.getRowCount(); row++) { - bSelected = (boolean) jTable1.getValueAt(row, COL.CHECK.ordinal()); - sStatus = jTable1.getValueAt(row, COL.STATUS.ordinal()).toString(); - if (bSelected && sStatus == status.toString()) { - iPendingTestsCount++; - } - } - return iPendingTestsCount; - } - - /** - * set the tests to stopped - */ - private void setToStopped() { - //No more tests to play. Stop - setButtonToStop(); - logger.log(Level.INFO, "End of tests."); - } - - /** - * get the first test currently in progress * - * @return properties of the test in progress */ - public String[] getTestInProgress() { - String[] dsTestProperties = {"", ""}; - //search for device name in table - try { - for (int row = 0; row <= jTable1.getRowCount() - 1; row++) { - if (jTable1.getValueAt(row, COL.STATUS.ordinal()).toString().equals(TestStatus.RUNNING.toString())) { - dsTestProperties[0] = jTable1.getValueAt(row, COL.DEVICENAME.ordinal()).toString(); - dsTestProperties[1] = jTable1.getValueAt(row, COL.TESTPATH.ordinal()).toString(); + public RunTest() { + //System.out.println("A0"); + } + + public void run() { + // code in the other thread, can reference "var" variable + executeTest(0); + } + + /** + * execute the selected tests in the list, starting from the position + * + * @param position row number from which to start executing tests + */ + private void executeTest(int position) { + boolean bSelected = false; + String sStartSequence, sStatus; + int[] selectedTestsRows = {}; + //scan through the table starting from 'position' and execute the first selected test found + int row = 0;// position; + if (row >= 0 && row < jTable1.getRowCount()) { + for (row = position; row < jTable1.getRowCount(); row++) { + bSelected = (boolean) jTable1.getValueAt(row, COL.CHECK.ordinal()); + sStartSequence = jTable1.getValueAt(row, COL.STARTSEQUENCE.ordinal()).toString(); + sStatus = jTable1.getValueAt(row, COL.STATUS.ordinal()).toString(); + //collect tests to be launched in parallel + //the test must be: selected, set as start with previous, pending. + //alternatively, the test must be: selected, first of the list. + + //System.out.println(String.valueOf(row) + "\t" + String.valueOf(bSelected) + "\t" + String.valueOf(selectedTestsRows.length) + "\t" + sStartSequence + "\t" + sStatus); + if (bSelected + && sStatus.equals(TestStatus.PENDING.toString()) + && (selectedTestsRows.length == 0 || //the test must be: selected, pending, first of the list. + sStartSequence.equals(StartSequence.TOGETHER.toString()))) { //or the test must be: selected, pending, set as start with previous + selectedTestsRows = append(selectedTestsRows, row); + } else if (bSelected + && sStatus.equals(TestStatus.PENDING.toString()) &&//if this test must be executed... + selectedTestsRows.length > 0 && //but there are already tests to be executed in parallel.... + (sStartSequence.equals(StartSequence.AFTER.toString()))) { //...and this test must be executed in series, then stop searching break; } } - } catch (Exception ex) { - this.setToStopped(); - SwingUtils.showMessage(this, "getTestInProgress()", ex.toString()); - } finally { - return dsTestProperties; - } - } - - /** - *returns the status of the specified test name for specified device name - * - * @param deviceName name of the device - * @param testPath path of the test file - * @return String containing the result returned by the test - */ - public String getResult(String deviceName, String testPath) { - String sStatus = ""; - int rowD = -1, colT = -1; - //search for device name in table - for (int row = 0; row <= jTable1.getRowCount() - 1; row++) { - if (deviceName.equals(jTable1.getValueAt(row, COL.DEVICENAME.ordinal()))) { - rowD = row; - break; - } - } - if (rowD >= 0) { - //search for test in table - if (testPath.equals(jTable1.getValueAt(rowD, COL.TESTPATH.ordinal()))) { - colT = COL.TESTNAME.ordinal(); - } - } - //get the test result - if (colT >= 0 && rowD >= 0) { - sStatus = jTable1.getValueAt(rowD, COL.STATUS.ordinal()).toString(); - } - return sStatus; - } - - /** - * visualise test status (columns status and icon) - */ - public void updateStatus() { - String sStatus; - boolean bSelected; - ImageIcon icon = null; - String sStart; - for (int row = 0; row <= jTable1.getRowCount() - 1; row++) { - bSelected = (boolean) jTable1.getValueAt(row, COL.CHECK.ordinal()); - sStart = String.valueOf(jTable1.getValueAt(row, COL.STARTSEQUENCE.ordinal())); - if (bSelected) { - sStatus = TestStatus.PENDING.toString(); - icon = TestStatus.PENDING.Icon(); - if (sStart == "") { - sStart = StartSequence.START_SEQ_AFTER.toString(); - } - } else { - sStatus = TestStatus.DISABLED.toString(); - icon = TestStatus.DISABLED.Icon(); - sStart = ""; - } - jTable1.setValueAt(bSelected, row, COL.CHECK.ordinal()); - jTable1.setValueAt(icon, row, COL.ICON.ordinal()); - jTable1.setValueAt(sStatus, row, COL.STATUS.ordinal()); - jTable1.setValueAt(sStart, row, COL.STARTSEQUENCE.ordinal()); - } - } - - /** - *launch the execution of the tests - */ - public void executeTests() { - RunTest runTest = new RunTest(); - Thread t = new Thread(runTest); - t.start(); - } - - /** - * - */ - public class RunTest implements Runnable { - - private HashMap mParameters; - //private HashMap args; - private HashMap hTests; - - /** - * - */ - public RunTest() { - //System.out.println("A0"); - } - - public void run() { - // code in the other thread, can reference "var" variable - executeTest(0); - } - - /** - *execute the selected tests in the list, starting from the position - * - *@param position row number from which to start executing tests - */ - private void executeTest(int position) { - boolean bSelected = false; - String sStartSequence, sStatus; - int[] selectedTestsRows = {}; - //scan through the table starting from 'position' and execute the first selected test found - int row = 0;// position; - if (row >= 0 && row < jTable1.getRowCount()) { - for (row = position; row < jTable1.getRowCount(); row++) { - bSelected = (boolean) jTable1.getValueAt(row, COL.CHECK.ordinal()); - sStartSequence = jTable1.getValueAt(row, COL.STARTSEQUENCE.ordinal()).toString(); - sStatus = jTable1.getValueAt(row, COL.STATUS.ordinal()).toString(); - //collect tests to be launched in parallel - //the test must be: selected, set as start with previous, pending. - //alternatively, the test must be: selected, first of the list. - - //System.out.println(String.valueOf(row) + "\t" + String.valueOf(bSelected) + "\t" + String.valueOf(selectedTestsRows.length) + "\t" + sStartSequence + "\t" + sStatus); - if (bSelected - && sStatus.equals(TestStatus.PENDING.toString()) - && (selectedTestsRows.length == 0 || //the test must be: selected, pending, first of the list. - sStartSequence.equals(StartSequence.START_SEQ_TOGETHER.toString()))) { //or the test must be: selected, pending, set as start with previous - selectedTestsRows = append(selectedTestsRows, row); - } else if (bSelected - && sStatus.equals(TestStatus.PENDING.toString()) &&//if this test must be executed... - selectedTestsRows.length > 0 && //but there are already tests to be executed in parallel.... - (sStartSequence.equals(StartSequence.START_SEQ_AFTER.toString()))) { //...and this test must be executed in series, then stop searching - break; - } - } - if (selectedTestsRows.length > 0) { //at least one test is selected: launch it (or them) - System.out.println("\n===================================================\n"); - executeParallelTestsGroup(selectedTestsRows); //last execution did not find a test file. Continue with next execution - executeTest(position + 1); - } - else{//no tests were selected. end. - setToStopped(); - } - } - } - - private HashMap buildMapFromTableRow(int row) { - String sDeviceName = jTable1.getValueAt(row, COL.DEVICENAME.ordinal()).toString(); - String sTestName = jTable1.getValueAt(row, COL.TESTNAME.ordinal()).toString(); - String sTestCaseName = jTable1.getValueAt(row, COL.TESTSUITE.ordinal()).toString(); - String sTestPath = jTable1.getValueAt(row, COL.TESTPATH.ordinal()).toString(); - HashMap mParameters = buildParametersMap(String.valueOf(jTable1.getValueAt(row, COL.TESTPARAMS.ordinal()))); - HashMap testArgs = new HashMap(); - //args.put("ret", ""); - testArgs.put("parameters", mParameters); - testArgs.put("test", sTestName); - testArgs.put("device", sDeviceName); - testArgs.put("testPath", sTestPath); - testArgs.put("status", false); - - return testArgs; - } - - //start all the tests in the rowsToExecute - private int executeParallelTestsGroup(int[] rowsToExecute) { - int iRet = -1; - HashMap args2 = new HashMap(); //this is the global map that will contain one map per test. - HashMap testArgs; //this is the map for a test. - RunTest runTest; - String sTestName = "", sDeviceName = "", sTestPath = ""; - for (int row : rowsToExecute) { - //System.out.println(String.valueOf(row) + "\t" + sDeviceName + "\t" + sTestName + "\t" + sTestCaseName + "\t" + String.valueOf(rowsToExecute.length)); - try { - testArgs = buildMapFromTableRow(row); - sTestName = (String) testArgs.get("test"); - sTestPath = (String) testArgs.get("testPath"); - sDeviceName = (String) testArgs.get("device"); - mParameters = (HashMap) testArgs.get("parameters"); - File f = new File(sTestPath); - if (!f.exists() || f.isDirectory()) { - logger.log(Level.SEVERE, "Cannot find test script: " + sTestPath); - showResult(sDeviceName, sTestPath, "Cannot find test script: " + sTestPath, TestStatus.FAILURE.toString()); - continue; - } - showResult(sDeviceName, sTestPath, "Test running", TestStatus.RUNNING.toString()); - //launch the test - if (!mParameters.isEmpty()) { - logger.log(Level.INFO, "Running test '" + sTestName + "' with the following parameters: " + mParameters.toString()); - System.out.println("Running test '" + sTestName + "' with the following parameters: " + mParameters.toString()); - } else { - logger.log(Level.INFO, "Running Test '" + sTestName + "'. No parameters found."); - System.out.println("Running test '" + sTestName + "'. No parameters found."); - } - args2.put(sTestPath, testArgs); - hTests = args2; - iRet = 0; - } catch (Exception ex) { - SwingUtils.showMessage(TestingList.this.getComponent(), "executeTest()", ex.toString()); - logger.log(Level.SEVERE, ex.toString()); - showResult(sDeviceName, sTestPath, ex.toString(), TestStatus.FAILURE.toString()); - setToStopped(); - } - } - try { - int iLastExecutedTestIndex = -1; - final String sParallelizeBegin = "(run,(str('"; - final String sParallelizeEnd = "'),))"; - String sParallelizeArguments; - try { - //System.out.println("A0.1"); - String sParallelizeCommand = "parallelize("; - int i = 0; - int iTotalEntries = hTests.entrySet().size(); - for (Map.Entry hTest : hTests.entrySet()) { - //setGlobalsVars(hTest.getValue()); //set global variables that can be read by all test scripts - sTestPath = hTest.getKey().toString(); - sTestPath = sTestPath.replace("\\", "\\\\"); - //System.out.println(hTest.getValue().get("test")); - sParallelizeCommand = sParallelizeCommand + "(run,(str('" + sTestPath; - //System.out.println("A"+i); - sParallelizeArguments = "globals(),{'parameters':'" + hTest.getValue().get("parameters") - + // sParallelizeArguments = "{'parameters':'"+hTest.getValue().get("parameters")+ - "','test':'" + hTest.getValue().get("test") - + "','device':'" + hTest.getValue().get("device") - + "','status':'" + hTest.getValue().get("status") + "'}"; - sParallelizeCommand = sParallelizeCommand + "')," + sParallelizeArguments; - i++; - if (i < iTotalEntries) { - sParallelizeCommand = sParallelizeCommand + ")),"; //between each "run" command - } else { - sParallelizeCommand = sParallelizeCommand + ")))"; //very last part of command "parallelize" - } - } - System.out.println(sParallelizeCommand); - Object ret; - //ret = eval("str(locals())"); - //ret = eval("str(globals())"); - ret = eval(sParallelizeCommand); - System.out.println("c"); -// Object ret = eval("parallelize((run,(str('"+sTestPath+"'),)), (run,('Motor Test 3 200ms',)))"); - //System.out.println("Ret = " + String.valueOf(ret)); - String sTestResult, sTestStatus; - //read the return mapping and put the result in the right table row - //System.out.println("ret type "+ret.getClass().toString() ); - //scan through all return mappings of all run tests - for (Object oTestRet : (ArrayList) ret) { - //check if the mapping of the selected test has all expected return values - if (((List) oTestRet).size() >= 4) { - //extract return data of the current test - sTestPath = String.valueOf(((List) oTestRet).get(0)); - sDeviceName = String.valueOf(((List) oTestRet).get(1)); - sTestResult = String.valueOf(((List) oTestRet).get(2)); - sTestStatus = String.valueOf(((List) oTestRet).get(3)); - //from the map of executed tests, get the test name (key is test path) - HashMap hTest = hTests.get(sTestPath); - sTestName = String.valueOf(hTest.get("test")); - } else { //problem, the test script does not return all the expected return values - String sErrorText = "Test " + sTestPath + " did not return all required return values"; - Logger.getLogger(TestingList.class.getName()).log(Level.SEVERE, null, sErrorText); - SwingUtils.showMessage(TestingList.this.getComponent(), "executeParallelTestsGroup()", sErrorText); - System.out.println(String.valueOf(sErrorText)); - //try to fetch at least first element of returned map. If fails, it will go to catch - sTestPath = String.valueOf(((List) oTestRet).get(0)); - sTestStatus = sErrorText; - sTestResult = "false"; - HashMap hTest = hTests.get(sTestPath); - sDeviceName = String.valueOf(hTest.get("device")); - sTestName = String.valueOf(hTest.get("test")); - } - System.out.println("Result: " + sDeviceName + "|" + sTestPath + "|" + sTestResult + "|" + sTestStatus); - iLastExecutedTestIndex = showResult(sDeviceName, sTestPath, sTestResult, sTestStatus); - } - } catch (ClassCastException ccex) { - Logger.getLogger(TestingList.class.getName()).log(Level.SEVERE, null, ccex); - SwingUtils.showMessage(TestingList.this.getComponent(), "executeParallelTestsGroup()", ccex.toString()); - //System.out.println(String.valueOf(ccex)); - if (!sDeviceName.isEmpty()) { - showResult(sDeviceName, sTestPath, ccex.toString(), TestStatus.FAILURE.toString()); - } - } catch (Exception ex) { - Logger.getLogger(TestingList.class.getName()).log(Level.SEVERE, null, ex); - SwingUtils.showMessage(TestingList.this.getComponent(), "executeParallelTestsGroup()", ex.toString()); - System.out.println(String.valueOf(ex)); - showResult(sDeviceName, sTestPath, ex.toString(), TestStatus.FAILURE.toString()); - } - - } catch (Exception ex) { - SwingUtils.showMessage(TestingList.this.getComponent(), "executeParallelTestsGroup(), run thread", ex.toString()); - logger.log(Level.SEVERE, ex.toString()); + if (selectedTestsRows.length > 0) { //at least one test is selected: launch it (or them) + System.out.println("\n===================================================\n"); + executeParallelTestsGroup(selectedTestsRows); //last execution did not find a test file. Continue with next execution + executeTest(position + 1); + } else {//no tests were selected. end. setToStopped(); } - return iRet; } } + private HashMap buildMapFromTableRow(int row) { + String sDeviceName = jTable1.getValueAt(row, COL.DEVICENAME.ordinal()).toString(); + String sTestName = jTable1.getValueAt(row, COL.TESTNAME.ordinal()).toString(); + String sTestCaseName = jTable1.getValueAt(row, COL.TESTSUITE.ordinal()).toString(); + String sTestPath = jTable1.getValueAt(row, COL.TESTPATH.ordinal()).toString(); + HashMap mParameters = buildParametersMap(String.valueOf(jTable1.getValueAt(row, COL.TESTPARAMS.ordinal()))); + HashMap testArgs = new HashMap(); + //args.put("ret", ""); + testArgs.put(testArgNames.PARAMETERS.toString(), mParameters); + testArgs.put(testArgNames.TEST.toString(), sTestName); + testArgs.put(testArgNames.DEVICE.toString(), sDeviceName); + testArgs.put(testArgNames.TEST_PATH.toString(), sTestPath); + testArgs.put(testArgNames.STATUS.toString(), false); + + return testArgs; + } + /** - * table management - */ - private void buildTable() { - String sDate = getNow(); - DefaultTableModel model = (DefaultTableModel) jTable1.getModel(); - jTable1.setModel(model); - - //Set up the combo box editor for the Start Sequence cells. - JComboBox comboBox = new JComboBox(); - comboBox.addItem(StartSequence.START_SEQ_AFTER.toString()); - comboBox.addItem(StartSequence.START_SEQ_TOGETHER.toString()); - jTable1.getColumnModel().getColumn(COL.STARTSEQUENCE.ordinal()).setCellEditor(new DefaultCellEditor(comboBox)); - //Set up tool tips for the sequence cells. - DefaultTableCellRenderer renderer = new DefaultTableCellRenderer(); - renderer.setToolTipText("Click for options"); - jTable1.getColumnModel().getColumn(COL.STARTSEQUENCE.ordinal()).setCellRenderer(renderer); - - jTable1.getColumnModel().getColumn(COL.ICON.ordinal()).setMaxWidth(27); - jTable1.getColumnModel().getColumn(COL.CHECK.ordinal()).setMaxWidth(27); - jTable1.getColumnModel().getColumn(COL.DEVICENAME.ordinal()).setPreferredWidth(30); - jTable1.getColumnModel().getColumn(COL.STATUS.ordinal()).setPreferredWidth(30); - hideColumn(COL.DEVICEDESCR); - hideColumn(COL.TESTPATH); - hideColumn(COL.TESTDESCR); - hideColumn(COL.TESTPARAMS); - hideColumn(COL.TESTHELP); - jTable1.setAutoCreateRowSorter(true); - updateStatus(); + * convert HashMap string separators to python dictionary string sepatators + * + * @param sParameters string coming from HashMap conaining the list of parameters to be passed to the test script. + * Example: + * {repeatTimes={description=Repeat N times, value=1}, midPoint={description=Middle point A, value=41.0}, spanFromMidPoint={description=B steps around middle point A, value=2.0}} + * @return string of dictionary in python syntax. This can be passed to the python test script. + * Example of output: + * {'repeatTimes':{'description':'Repeat N times','value':'1'},'midPoint':{'description':'Middle point A','value':'41.0'},'spanFromMidPoint':{'description':'B steps around middle point A','value':'2.0'} + */ + private String convertParametersMapToPythonMap(String sParameters){ + String sPythonParams = sParameters; + sPythonParams = sPythonParams.replace(", " , ","); + sPythonParams = sPythonParams.replace(" ," , ","); + sPythonParams = sPythonParams.replace("{{" , "#@"); + sPythonParams = sPythonParams.replace("}}" , "@#"); + sPythonParams = sPythonParams.replace("}," , "@%#"); + sPythonParams = sPythonParams.replace(",{" , "#%@"); + sPythonParams = sPythonParams.replace("={" , "^%&"); + sPythonParams = sPythonParams.replace("=}" , "&%^"); + sPythonParams = sPythonParams.replace("," , "','"); + sPythonParams = sPythonParams.replace("{" , "{'"); + sPythonParams = sPythonParams.replace("}" , "'}"); + sPythonParams = sPythonParams.replace("=" , "':'"); + sPythonParams = sPythonParams.replace("^%&", "':{'"); + sPythonParams = sPythonParams.replace("&%^", "'}:'"); + sPythonParams = sPythonParams.replace("#@" , "{{'"); + sPythonParams = sPythonParams.replace("@#" , "'}}"); + sPythonParams = sPythonParams.replace("@%#", "'},'"); + sPythonParams = sPythonParams.replace("#%@", "',{'"); + return sPythonParams; } - private void hideColumn(COL column) { - jTable1.getColumnModel().getColumn(column.ordinal()).setMinWidth(0); - jTable1.getColumnModel().getColumn(column.ordinal()).setMaxWidth(0); - } - - //append test info to table - private void addToTable(String deviceName, - String deviceDescription, - String testSuite, - String testName, - String testParams, - String testDescription, - String testHelp) { - String sDate = ""; - if (testName.equals("") || deviceName.equals("")) { - return; + /** start all the tests in the array rowsToExecute. + * all tests in the listed row indexes will be started at the same time. + * + * @param rowsToExecute array of indexes relative to the test rows in the table. + * The indexes in the array will execute the test in corresponding row + * @return return value: 0 means ok, <0 means problem + */ + private int executeParallelTestsGroup(int[] rowsToExecute) { + int iRet = -1; + HashMap args2 = new HashMap(); //this is the global map that will contain one map per test. + HashMap testArgs; //this is the map for a test. + RunTest runTest; + String sTestName = "", sDeviceName = "", sTestPath = ""; + for (int row : rowsToExecute) { + //System.out.println(String.valueOf(row) + "\t" + sDeviceName + "\t" + sTestName + "\t" + sTestCaseName + "\t" + String.valueOf(rowsToExecute.length)); + try { + testArgs = buildMapFromTableRow(row); + sTestName = (String) testArgs.get(testArgNames.TEST.toString()); + sTestPath = (String) testArgs.get(testArgNames.TEST_PATH.toString()); + sDeviceName = (String) testArgs.get(testArgNames.DEVICE.toString()); + mParameters = (HashMap) testArgs.get(testArgNames.PARAMETERS.toString()); + File f = new File(sTestPath); + if (!f.exists() || f.isDirectory()) { + logger.log(Level.SEVERE, "Cannot find test script: " + sTestPath); + showResult(sDeviceName, sTestPath, "Cannot find test script: " + sTestPath, TestStatus.FAILURE.toString()); + continue; + } + showResult(sDeviceName, sTestPath, "Test running", TestStatus.RUNNING.toString()); + //launch the test + if (!mParameters.isEmpty()) { + logger.log(Level.INFO, "Running test '" + sTestName + "' with the following parameters: " + mParameters.toString()); + System.out.println("Running test '" + sTestName + "' with the following parameters: " + mParameters.toString()); + } else { + logger.log(Level.INFO, "Running Test '" + sTestName + "'. No parameters found."); + System.out.println("Running test '" + sTestName + "'. No parameters found."); + } + args2.put(sTestPath, testArgs); + hTests = args2; + iRet = 0; + } catch (Exception ex) { + SwingUtils.showMessage(TestingList.this, "executeTest()", ex.toString()); + logger.log(Level.SEVERE, ex.toString()); + showResult(sDeviceName, sTestPath, ex.toString(), TestStatus.FAILURE.toString()); + setToStopped(); + } } - ImageIcon icon = null;// new ImageIcon(getClass().getResource("/icons/button_pause-16px.png")); - DefaultTableModel model = (DefaultTableModel) jTable1.getModel(); - String testPath = FilenameUtils.separatorsToSystem(TESTS_TESTS_DEFAULT_DIR + testSuite + "/" + testName + "/" + testName + ".py"); - model.addRow(new Object[]{false, "", sDate, deviceName, deviceDescription, testSuite, testName, testPath, testParams, testDescription, testHelp, "", "Pending", icon}); - jTable1.setModel(model); - updateStatus(); - } + try { + int iLastExecutedTestIndex = -1; + final String sParallelizeBegin = "(run,(str('"; + final String sParallelizeEnd = "'),))"; + String sParallelizeArguments; + try { + //System.out.println("A0.1"); + String sParallelizeCommand = "parallelize("; + int i = 0; + int iTotalEntries = hTests.entrySet().size(); + HashMap args = new HashMap(); + for (Map.Entry hTest : hTests.entrySet()) { + //REMOVE this when local parameters will work + /* + args.put("parameters", hTest.getValue().get("parameters")); + args.put("device", hTest.getValue().get(testArgNames.DEVICE.toString())); + args.put("test", hTest.getValue().get(testArgNames.TEST.toString())); + args.put("ret", ""); + args.put("status", hTest.getValue().get(testArgNames.STATUS.toString())); + setGlobalsVars(hTest.getValue()); //set global variables that can be read by all test scripts + setGlobalsVars(args); //set global variables that can be read by all test scripts + //end REMOVE +*/ + sTestPath = hTest.getKey().toString(); + sTestPath = sTestPath.replace("\\", "\\\\"); + //System.out.println(hTest.getValue().get("test")); + sParallelizeCommand = sParallelizeCommand + "(run,(str('" + sTestPath; + //System.out.println("A"+i); + sParallelizeArguments = "None, {'parameters':" + convertParametersMapToPythonMap(hTest.getValue().get("parameters").toString()) + + ",'test':'" + hTest.getValue().get(testArgNames.TEST.toString()) + + "','device':'" + hTest.getValue().get(testArgNames.DEVICE.toString()) + + "','status':'" + hTest.getValue().get(testArgNames.STATUS.toString()) + "'}"; + //without parameters: + /* + sParallelizeArguments = "None" + + ",{'test':'" + hTest.getValue().get(testArgNames.TEST.toString()) + + "','device':'" + hTest.getValue().get(testArgNames.DEVICE.toString()) + + "','status':'" + hTest.getValue().get(testArgNames.STATUS.toString()) + "'}"; + */ + //this to remove arguments. COMMENT OUT when arguments work well + //sParallelizeArguments = ""; + sParallelizeCommand = sParallelizeCommand + "')," + sParallelizeArguments; + i++; + if (i < iTotalEntries) { + sParallelizeCommand = sParallelizeCommand + ")),"; //between each "run" command + } else { + sParallelizeCommand = sParallelizeCommand + ")))"; //very last part of command "parallelize" + } + } + System.out.println(sParallelizeCommand); + Object ret; + //ret = eval("str(locals())"); + //ret = eval("str(globals())"); + //ret = eval("run('dummy.py')"); + ret = eval(sParallelizeCommand); + System.out.println("c"); +// Object ret = eval("parallelize((run,(str('"+sTestPath+"'),)), (run,('Motor Test 3 200ms',)))"); + //System.out.println("Ret = " + String.valueOf(ret)); + String sTestResult, sTestStatus; + //read the return mapping and put the result in the right table row + //System.out.println("ret type "+ret.getClass().toString() ); + //scan through all return mappings of all run tests + for (Object oTestRet : (ArrayList) ret) { + //check if the mapping of the selected test has all expected return values + if (((List) oTestRet).size() >= 4) { + //extract return data of the current test + sTestPath = String.valueOf(((List) oTestRet).get(0)); + sDeviceName = String.valueOf(((List) oTestRet).get(1)); + sTestResult = String.valueOf(((List) oTestRet).get(2)); + sTestStatus = String.valueOf(((List) oTestRet).get(3)); + //from the map of executed tests, get the test name (key is test path) + HashMap hTest = hTests.get(sTestPath); + sTestName = String.valueOf(hTest.get(testArgNames.TEST.toString())); + } else { //problem, the test script does not return all the expected return values + String sErrorText = "Test " + sTestPath + " did not return all required return values"; + Logger.getLogger(TestingList.class.getName()).log(Level.SEVERE, null, sErrorText); + SwingUtils.showMessage(TestingList.this, "executeParallelTestsGroup()", sErrorText); + System.out.println(String.valueOf(sErrorText)); + //try to fetch at least first element of returned map. If fails, it will go to catch + sTestPath = String.valueOf(((List) oTestRet).get(0)); + sTestStatus = sErrorText; + sTestResult = "false"; + HashMap hTest = hTests.get(sTestPath); + sDeviceName = String.valueOf(hTest.get(testArgNames.DEVICE.toString())); + sTestName = String.valueOf(hTest.get(testArgNames.TEST.toString())); + } + System.out.println("Result: " + sDeviceName + "|" + sTestPath + "|" + sTestResult + "|" + sTestStatus); + iLastExecutedTestIndex = showResult(sDeviceName, sTestPath, sTestResult, sTestStatus); + } + } catch (ClassCastException ccex) { + Logger.getLogger(TestingList.class.getName()).log(Level.SEVERE, null, ccex); + SwingUtils.showMessage(TestingList.this, "executeParallelTestsGroup()", ccex.toString()); + //System.out.println(String.valueOf(ccex)); + if (!sDeviceName.isEmpty()) { + showResult(sDeviceName, sTestPath, ccex.toString(), TestStatus.FAILURE.toString()); + } + } catch (Exception ex) { + Logger.getLogger(TestingList.class.getName()).log(Level.SEVERE, null, ex); + SwingUtils.showMessage(TestingList.this, "executeParallelTestsGroup()", ex.toString()); + System.out.println(String.valueOf(ex)); + showResult(sDeviceName, sTestPath, ex.toString(), TestStatus.FAILURE.toString()); + } - /** - *get the current time in format like 2015/07/02 15:59:43 - * - * @return formatted time - */ - public String getNow() { - DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); - Date date = new Date(); - return dateFormat.format(date); + } catch (Exception ex) { + SwingUtils.showMessage(TestingList.this, "executeParallelTestsGroup(), run thread", ex.toString()); + logger.log(Level.SEVERE, ex.toString()); + setToStopped(); + } + return iRet; } + } - /** - *get the current time in format like 20150702155943 - * - * @return time with sortable format - */ - public String getnow() { - DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss"); - Date date = new Date(); - return dateFormat.format(date); + /** + * table management + */ + private void buildTable() { + String sDate = getNow(); + DefaultTableModel model = (DefaultTableModel) jTable1.getModel(); + jTable1.setModel(model); + + //Set up the combo box editor for the Start Sequence cells. + JComboBox comboBox = new JComboBox(); + comboBox.addItem(StartSequence.AFTER.toString()); + comboBox.addItem(StartSequence.TOGETHER.toString()); + jTable1.getColumnModel().getColumn(COL.STARTSEQUENCE.ordinal()).setCellEditor(new DefaultCellEditor(comboBox)); + //Set up tool tips for the sequence cells. + DefaultTableCellRenderer renderer = new DefaultTableCellRenderer(); + renderer.setToolTipText("Click for options"); + jTable1.getColumnModel().getColumn(COL.STARTSEQUENCE.ordinal()).setCellRenderer(renderer); + + jTable1.getColumnModel().getColumn(COL.STARTSEQUENCE.ordinal()).setPreferredWidth(30); + jTable1.getColumnModel().getColumn(COL.ICON.ordinal()).setMaxWidth(27); + jTable1.getColumnModel().getColumn(COL.CHECK.ordinal()).setMaxWidth(27); + jTable1.getColumnModel().getColumn(COL.DEVICENAME.ordinal()).setPreferredWidth(30); + jTable1.getColumnModel().getColumn(COL.STATUS.ordinal()).setPreferredWidth(20); + hideColumn(COL.DEVICEDESCR); + hideColumn(COL.TESTPATH); + hideColumn(COL.TESTDESCR); + hideColumn(COL.TESTPARAMS); + hideColumn(COL.TESTHELP); + jTable1.setAutoCreateRowSorter(true); + updateStatus(); + } + + private void hideColumn(COL column) { + jTable1.getColumnModel().getColumn(column.ordinal()).setMinWidth(0); + jTable1.getColumnModel().getColumn(column.ordinal()).setMaxWidth(0); + } + + //append test info to table + private void addToTable(String deviceName, + String deviceDescription, + String testSuite, + String testName, + String testParams, + String testDescription, + String testHelp) { + String sDate = ""; + if (testName.equals("") || deviceName.equals("")) { + return; } + ImageIcon icon = null;// new ImageIcon(getClass().getResource("/icons/button_pause-16px.png")); + DefaultTableModel model = (DefaultTableModel) jTable1.getModel(); + //String testPath = FilenameUtils.separatorsToSystem(TESTS_TESTS_DEFAULT_DIR + testSuite + "/" + testName + "/" + testName + ".py"); + String testPath = Paths.get(TESTS_TESTS_DEFAULT_DIR.toString(), testSuite, testName, testName + ".py").toString(); + model.addRow(new Object[]{false, "", sDate, deviceName, deviceDescription, testSuite, testName, testPath, testParams, testDescription, testHelp, "", "Pending", icon}); + jTable1.setModel(model); + updateStatus(); + } - /** - *scan tests directory, scan devices directory, search for their test cases and scan for tests. - * - * @throws FileNotFoundException - * @throws IOException - */ - public void loadTests() throws FileNotFoundException, IOException { - Properties propDevice = new Properties(); - Properties propTest = new Properties(); - String fileName = TESTS_DEVICES_DEFAULT_DIR; - File folder = new File(fileName); - File testsFolder = null; - String sTestName; - int iCounter = 0; + /** + * get the current time in format like 2015/07/02 15:59:43 + * + * @return formatted time + */ + public String getNow() { + DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); + Date date = new Date(); + return dateFormat.format(date); + } + + /** + * get the current time in format like 20150702155943 + * + * @return time with sortable format + */ + public String getnow() { + DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss"); + Date date = new Date(); + return dateFormat.format(date); + } + + /** + * scan tests directory, scan devices directory, search for their test cases + * and scan for tests. + * + * @throws FileNotFoundException + * @throws IOException + */ + public void loadTests() throws FileNotFoundException, IOException { + Properties propDevice = new Properties(); + Properties propTest = new Properties(); + //String fileName = TESTS_DEVICES_DEFAULT_DIR; + //File folder = new File(fileName); + File testsFolder = null; + String sTestName; + int iCounter = 0; //search devices and their tests - //Scan the list of devices - File[] listOfFiles = folder.listFiles(); - for (File listOfFile : listOfFiles) { - propDevice.clear(); - if (listOfFile.isFile()) { - } else if (listOfFile.isDirectory()) { - File configFile = new File(listOfFile.getPath() + FilenameUtils.separatorsToSystem("/.config")); - if (configFile.exists() && !configFile.isDirectory()) { - InputStream is = new FileInputStream(configFile); - propDevice.load(is); - //config of device was loaded. now load the config of each test belonging to the device - sTestName = TESTS_TESTS_DEFAULT_DIR + propDevice.getProperty("tests"); - testsFolder = new File(sTestName); - if (testsFolder.exists() && testsFolder.isDirectory()) { - File[] listOfTests = testsFolder.listFiles(); - for (File listOfTest : listOfTests) { - propTest.clear(); - if (listOfTest.isDirectory()) { - configFile = new File(listOfTest.getPath() + FilenameUtils.separatorsToSystem("/.config")); - if (configFile.exists() && !configFile.isDirectory()) { - InputStream ist = new FileInputStream(configFile); - propTest.load(ist); - addToTable(propDevice.getProperty("name"), - propDevice.getProperty("description"), - propDevice.getProperty("tests"), - propTest.getProperty("name"), - propTest.getProperty("parameters"), - propTest.getProperty("description"), - propTest.getProperty("help")); - iCounter++; - } + //Scan the list of devices + File[] listOfFiles = TESTS_DEVICES_DEFAULT_DIR.toFile().listFiles(); + for (File listOfFile : listOfFiles) { + propDevice.clear(); + if (listOfFile.isFile()) { + } else if (listOfFile.isDirectory()) { + File configFile = new File(listOfFile.getPath() + FilenameUtils.separatorsToSystem("/.config")); + if (configFile.exists() && !configFile.isDirectory()) { + InputStream is = new FileInputStream(configFile); + propDevice.load(is); + //config of device was loaded. now load the config of each test belonging to the device + //sTestName = TESTS_TESTS_DEFAULT_DIR + propDevice.getProperty("tests"); + //testsFolder = new File(sTestName); + testsFolder = Paths.get(TESTS_TESTS_DEFAULT_DIR.toString(), propDevice.getProperty("tests")).toFile(); + if (testsFolder.exists() && testsFolder.isDirectory()) { + File[] listOfTests = testsFolder.listFiles(); + for (File listOfTest : listOfTests) { + propTest.clear(); + if (listOfTest.isDirectory()) { + configFile = new File(listOfTest.getPath() + FilenameUtils.separatorsToSystem("/.config")); + if (configFile.exists() && !configFile.isDirectory()) { + InputStream ist = new FileInputStream(configFile); + propTest.load(ist); + addToTable(propDevice.getProperty("name"), + propDevice.getProperty("description"), + propDevice.getProperty("tests"), + propTest.getProperty("name"), + propTest.getProperty("parameters"), + propTest.getProperty("description"), + propTest.getProperty("help")); + iCounter++; } } } } } } - logger.log(Level.INFO, iCounter + " tests loaded."); } + logger.log(Level.INFO, iCounter + " tests loaded."); + } - /** - * Build a map with optional parameters to be passed to the testing - * script. The map is like this: - * parameters - * \_ name - * | \_ value - * | \_ description - * \_ name - * | \_ value - * | \_ description - * ... - * the name 'name' is the mapping key. 'value' and 'description' are constant - * mapping keys of a nested map. - * - * @param parametersString string containing the parameters. Syntax: - * name:value:description[;name:value:description;...] - */ - private HashMap buildParametersMap(String parametersString) { - HashMap mParameters = new HashMap(); // contains name and attributes - HashMap mParameterAttributes = new HashMap(); //contians value and description - String[] dsParameterAttributes = null; - String[] dsParameters = parametersString.split(";"); - for (String sParameter : dsParameters) { - dsParameterAttributes = sParameter.split(":"); - if (dsParameterAttributes.length > 2) { - mParameterAttributes = new HashMap(); - mParameterAttributes.put("value", (Object) dsParameterAttributes[1]); - mParameterAttributes.put("description", dsParameterAttributes[2]); - //add parameter name and attributes (value + description) - mParameters.put(dsParameterAttributes[0], mParameterAttributes); - } - } - return mParameters; - } - - /** - * Save current setup in a file. - * The current position of table rows is also saved. - */ - public void saveSettings() { - final JFileChooser fc = new JFileChooser(); - - int returnVal = fc.showSaveDialog(NetbeansPluginPanel.this); - - if (returnVal == JFileChooser.APPROVE_OPTION) { - File file = fc.getSelectedFile(); - saveSettings(file); - } - } - - /** - * Save current setup in a file. - * The current position of table rows is also saved. - * - * @param file file containing the settings - */ - private void saveSettings(File file) { - DefaultTableModel tableModel = (DefaultTableModel) jTable1.getModel(); - try { - ObjectOutputStream out = new ObjectOutputStream( - new FileOutputStream(file)); - out.writeObject(tableModel.getDataVector()); - out.close(); - } catch (Exception ex) { - ex.printStackTrace(); + /** + * Build a map with optional parameters to be passed to the testing script. + * The map is like this: parameters \_ name | \_ value | \_ description \_ + * name | \_ value | \_ description ... the name 'name' is the mapping key. + * 'value' and 'description' are constant mapping keys of a nested map. + * + * @param parametersString string containing the parameters. Syntax: + * name:value:description[;name:value:description;...] + */ + private HashMap buildParametersMap(String parametersString) { + HashMap mParameters = new HashMap(); // contains name and attributes + HashMap mParameterAttributes = new HashMap(); //contians value and description + String[] dsParameterAttributes = null; + String[] dsParameters = parametersString.split(";"); + for (String sParameter : dsParameters) { + dsParameterAttributes = sParameter.split(":"); + if (dsParameterAttributes.length > 2) { + mParameterAttributes = new HashMap(); + mParameterAttributes.put("value", (Object) dsParameterAttributes[1]); + mParameterAttributes.put("description", dsParameterAttributes[2]); + //add parameter name and attributes (value + description) + mParameters.put(dsParameterAttributes[0], mParameterAttributes); } } + return mParameters; + } - /** - * Save current setup in a file. - * The current position of table rows is also saved. - */ - public void loadSettings() { - final JFileChooser fc = new JFileChooser(); - int returnVal = fc.showOpenDialog(NetbeansPluginPanel.this); - if (returnVal == JFileChooser.APPROVE_OPTION) { - File file = fc.getSelectedFile(); - loadSettings(file); - } + /** + * Save current setup in a file. The current position of table rows is also + * saved. + */ + public void saveSettings() { + final JFileChooser fc = new JFileChooser(); + int returnVal = fc.showSaveDialog(this); + if (returnVal == JFileChooser.APPROVE_OPTION) { + File file = fc.getSelectedFile(); + saveSettings(file); } + } - /** - * Save current setup in a file. - * The current position of table rows is also saved. - * - * @param file file containing the settings - */ - private void loadSettings(File file) { - DefaultTableModel tableModel = (DefaultTableModel) jTable1.getModel(); - try { - ObjectInputStream in = new ObjectInputStream(new FileInputStream(file)); - Vector rowData = (Vector) in.readObject(); - Iterator itr = rowData.iterator(); - //clear table - tableModel.getDataVector().removeAllElements(); - tableModel.fireTableDataChanged(); - //rewrite table - while (itr.hasNext()) { - tableModel.addRow((Vector) itr.next()); - } - in.close(); - } catch (Exception ex) { - ex.printStackTrace(); - SwingUtils.showMessage(this, "loadSettings()", ex.toString()); - } + /** + * Save current setup in a file. The current position of table rows is also + * saved. + * + * @param file file containing the settings + */ + private void saveSettings(File file) { + DefaultTableModel tableModel = (DefaultTableModel) jTable1.getModel(); + try { + ObjectOutputStream out = new ObjectOutputStream( + new FileOutputStream(file)); + out.writeObject(tableModel.getDataVector()); + out.close(); + } catch (Exception ex) { + ex.printStackTrace(); } - + } + + /** + * Save current setup in a file. The current position of table rows is also + * saved. + */ + public void loadSettings() { + final JFileChooser fc = new JFileChooser(); + int returnVal = fc.showOpenDialog(this); + if (returnVal == JFileChooser.APPROVE_OPTION) { + File file = fc.getSelectedFile(); + loadSettings(file); + } + } + + /** + * Save current setup in a file. The current position of table rows is also + * saved. + * + * @param file file containing the settings + */ + private void loadSettings(File file) { + DefaultTableModel tableModel = (DefaultTableModel) jTable1.getModel(); + try { + ObjectInputStream in = new ObjectInputStream(new FileInputStream(file)); + Vector rowData = (Vector) in.readObject(); + Iterator itr = rowData.iterator(); + //clear table + tableModel.getDataVector().removeAllElements(); + tableModel.fireTableDataChanged(); + //rewrite table + while (itr.hasNext()) { + tableModel.addRow((Vector) itr.next()); + } + in.close(); + } catch (Exception ex) { + ex.printStackTrace(); + SwingUtils.showMessage(this, "loadSettings()", ex.toString()); + } + } //end of class - } }