Cleaned up Sim Control Panel test suite

This commit is contained in:
Marcus Rockwell 2024-09-13 13:50:50 -05:00
parent 25936b0301
commit 0fe1e05f22
6 changed files with 162 additions and 1109 deletions

View File

@ -1,100 +1,117 @@
package trick.common;
import trick.common.fixtures.FontChooserFixture;
import trick.common.ui.components.FontChooser;
import trick.simcontrol.SimControlApplication;
import trick.simcontrol.StubbedSimControlApplication;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Component;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.Dimension;
import java.awt.event.KeyEvent;
import java.awt.GraphicsEnvironment;
import java.awt.Toolkit;
import java.beans.Transient;
import java.util.ArrayList;
import javax.swing.Action;
import javax.swing.ActionMap;
import org.jdesktop.application.ResourceMap;
import javax.swing.JButton;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JTextField;
import javax.swing.JToggleButton;
import javax.swing.text.JTextComponent;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
import trick.common.ActionInfo;
import org.assertj.swing.core.GenericTypeMatcher;
import org.assertj.swing.core.KeyPressInfo;
import org.assertj.swing.exception.ComponentLookupException;
import org.assertj.swing.fixture.AbstractComponentFixture;
import org.assertj.swing.fixture.ComponentContainerFixture;
import org.assertj.swing.fixture.DialogFixture;
import org.assertj.swing.fixture.JButtonFixture;
import org.assertj.swing.fixture.JMenuItemFixture;
import org.assertj.swing.fixture.JOptionPaneFixture;
import org.assertj.swing.fixture.JPanelFixture;
import org.assertj.swing.fixture.JTextComponentFixture;
import org.assertj.swing.fixture.JToggleButtonFixture;
import org.assertj.swing.fixture.JToolBarFixture;
import org.assertj.swing.fixture.FrameFixture;
import org.assertj.swing.fixture.MouseInputSimulationFixture;
import org.assertj.swing.junit.testcase.AssertJSwingJUnitTestCase;
public abstract class ApplicationTest {
protected ArrayList<ActionInfo> coreActionInfo, supportActionInfo, miscActionInfo;
protected ActionMap actionContext;
protected ResourceMap resourceContext;
import org.jdesktop.swingx.JXFindBar;
import org.jdesktop.swingx.JXEditorPane;
public static String getTrickHome() {
String path;
import org.junit.BeforeClass;
import org.junit.Test;
// Getting TRICK_HOME environment variable
path = System.getenv("TRICK_HOME");
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assumptions.assumeThat;
import static org.assertj.swing.finder.WindowFinder.findFrame;
import static org.assertj.swing.launcher.ApplicationLauncher.application;
// Getting Trick's home directory if TRICK_HOME isn't set
if(path != null) {
if(path.endsWith("/"))
path.substring(0, path.length() - 1);
} else {
path = System.getProperty("user.dir");
int cutoff = path.indexOf("/trick_source");
path = (cutoff > 0) ? path.substring(0, cutoff) : "";
}
return path;
}
public boolean compStringArray(String[] a, String[] b) {
boolean same = true;
for(int i = 0; i < a.length && i < b.length; i++) {
same = same && sameLetters(a[i], b[i]);
if(!same) return same;
}
return same;
}
public boolean sameLetters(String str1, String str2) {
String a = str1.replaceAll("\\s+", "").toLowerCase(),
b = str2.replaceAll("\\s+", "").toLowerCase();
return a.equals(b);
}
public abstract class ApplicationTest extends AssertJSwingJUnitTestCase {
protected FrameFixture mainFrame;
public static void sleep(long ms) {
try {Thread.sleep(ms);} catch(Exception ignored) {}
}
private String getActionText(Action action) {
return (String)action.getValue(Action.NAME);
protected FrameFixture getFrameByTitle(String title) {
FrameFixture frame = findFrame(new GenericTypeMatcher<Frame>(Frame.class) {
protected boolean isMatching(Frame frame) {
return title.equals(frame.getTitle()) && frame.isShowing();
}
}).using(robot());
return frame;
}
private String getActionShortDescription(Action action) {
return (String)action.getValue(Action.SHORT_DESCRIPTION);
protected JButtonFixture getButtonByText(ComponentContainerFixture container, String text) {
JButtonFixture button;
try {
button = container.button(new GenericTypeMatcher<JButton>(JButton.class) {
@Override
protected boolean isMatching(JButton button) {
return text.equals(button.getText());
}
});
} catch (ComponentLookupException e) {
return null;
}
private Action getActionFromKey(String actionKey) {
String errMsg = String.format("No ActionMap set. Action '%s' cannot be searched for.\n", actionKey);
// assumeNotNull(errMsg, actionContext);
return actionContext.get(actionKey);
return button;
}
protected void setupExpectedActionInfo() {
coreActionInfo = new ArrayList<ActionInfo>();
supportActionInfo = new ArrayList<ActionInfo>();
miscActionInfo = new ArrayList<ActionInfo>();
getCoreActionInfo();
getSupportActionInfo();
getMiscActionInfo();
protected JButtonFixture getButtonByText(String text) {
return getButtonByText(mainFrame, text);
}
// protected void verifyActionInfo(ActionInfo aInfo) {
// Action action = getActionFromKey(aInfo.name);
// assumeNotNull(String.format("ActionMap.get(\"%s\") = null", aInfo.name), action);
protected JToggleButtonFixture getToggleButtonByText(ComponentContainerFixture container, String text) {
JToggleButtonFixture button;
try {
button = container.toggleButton(new GenericTypeMatcher<JToggleButton>(JToggleButton.class) {
@Override
protected boolean isMatching(JToggleButton button) {
return text.equals(button.getText());
}
});
} catch (ComponentLookupException e) {
return null;
}
return button;
}
protected JToggleButtonFixture getToggleButtonByText(String text) {
return getToggleButtonByText(mainFrame, text);
}
// String actualText = getActionText(action);
// String actualDesc = getActionShortDescription(action);
// assertEquals(aInfo.text, actualText);
// assertEquals(aInfo.description, actualDesc);
// }
// protected void verifyResourceInfo(String key, String expectedStr) {
// String resourceText, errMsg = String.format("No ResourceMap set. Resource '%s' cannot be searched for.\n", key);
// assumeNotNull(errMsg, resourceContext);
// resourceText = resourceContext.getString(key);
// assertEquals(expectedStr, resourceText);
// }
protected abstract void getCoreActionInfo();
protected abstract void getSupportActionInfo();
protected abstract void getMiscActionInfo();
}

View File

@ -1,102 +0,0 @@
package trick.common;
import java.awt.AWTException;
import java.awt.Component;
import java.awt.Point;
import java.awt.Robot;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.util.Timer;
import java.util.TimerTask;
public class GUIController extends Robot {
private long depressTime;
public GUIController() throws AWTException {
super();
depressTime = 25;
}
public GUIController(long ms) throws AWTException {
super();
depressTime = ms;
}
public void typeString(String entry) {
int keycode;
String upperCaseSpecial = "~!@#$%^&*()_+{}|:\"<>?";
for (char c : entry.toCharArray()) {
if (Character.isUpperCase(c) || upperCaseSpecial.indexOf(c) >= 0)
keyPress(KeyEvent.VK_SHIFT);
else
keyRelease(KeyEvent.VK_SHIFT);
switch(c) {
case '\n' : keycode = KeyEvent.VK_ENTER; break;
default: keycode = KeyEvent.getExtendedKeyCodeForChar(c); break;
}
keyTap(keycode);
sleep(25);
}
keyRelease(KeyEvent.VK_SHIFT);
}
public void clearTextField() {
keyPress(KeyEvent.VK_CONTROL);
sleep(depressTime);
keyTap('A');
sleep(depressTime);
keyRelease(KeyEvent.VK_CONTROL);
sleep(depressTime);
keyTap(KeyEvent.VK_BACK_SPACE);
}
public void keyTap(int keycode) {
keyPress(keycode);
sleep(depressTime);
keyRelease(keycode);
}
public void delayedKeyTap(int keycode, long delay) {
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() { keyTap(keycode); }
}, delay);
}
public void delayedTypeString(String entry, long delay) {
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() { typeString(entry); }
}, delay);
}
public void mouseClick(int buttons) {
mousePress(buttons);
sleep(depressTime);
mouseRelease(buttons);
}
public void mouseClickAt(int buttons, Point pos) {
mouseMove(pos.x, pos.y);
mouseClick(buttons);
}
public void mouseClickAt(int buttons, Component comp) {
Point pos = comp.getLocationOnScreen();
pos.translate(comp.getWidth()/2, comp.getHeight()/2);
mouseClickAt(buttons, pos);
}
private void sleep(long ms) {
try { Thread.sleep(ms); } catch (Exception ignored) { }
}
}

View File

@ -1,38 +0,0 @@
package trick.simcontrol;
import org.jdesktop.application.Application;
import trick.simcontrol.utils.SimControlActionController;
import java.awt.*;
import java.awt.event.ActionEvent;
import javax.swing.Action;
import javax.swing.AbstractAction;
public class HeadlessSimControlApplication extends SimControlApplication {
public HeadlessSimControlApplication() {
this("", -1);
}
public HeadlessSimControlApplication(String hostname, int portNum) {
super.setHostPort(hostname, portNum);
actionController = new SimControlActionController();
}
@Override
protected Action getAction(String key) {
return new AbstractAction() {
public void actionPerformed(ActionEvent UNUSED) {}
};
}
@Override
protected void updateGUI() { /* UNUSED */ }
@Override
protected void startStatusMonitors() { /* UNUSED */}
}

View File

@ -1,590 +0,0 @@
package trick.simcontrol;
import java.awt.GraphicsEnvironment;
import java.awt.event.KeyEvent;
import java.beans.Transient;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Arrays;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.jdesktop.application.Application;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
import static org.junit.Assume.assumeTrue;
import static org.junit.Assume.assumeNotNull;
import trick.common.ApplicationTest;
import trick.common.SimulationInterface;
import trick.common.utils.VariableServerConnection;
import trick.common.ActionInfo;
/**
*
* Test SimControlApplication life cycle.
*
* @author hchen
* @intern mrockwell2
*
*/
public class SimControlApplicationTest extends ApplicationTest {
private final static String SIM_DIR = "/test/SIM_gui_testing";
private final ByteArrayOutputStream errContent = new ByteArrayOutputStream();
private final PrintStream originalErr = System.err;
private final int MODE_FREEZE = 1,
MODE_RUN = 5;
private static SimControlApplication simControl;
private static VariableServerConnection varserv;
private static Process simProc;
private static String host;
private static int port;
@BeforeClass
public static void setUpBeforeClass() {
String fullDir = getTrickHome() + SIM_DIR;
simControl = null;
SimulationInterface.cleanSim(fullDir);
SimulationInterface.compileSim(fullDir);
simProc = SimulationInterface.startSim(fullDir, "RUN_test/input.py");
sleep(1000);
try {
Scanner infoReader = new Scanner(new File(fullDir + "/socket_info"));
String line = infoReader.nextLine();
host = line.split(":")[0];
port = Integer.parseInt(line.split(":")[1]);
varserv = new VariableServerConnection(host, port);
} catch (Exception e) {
System.err.println(e.getMessage());
host = "";
port = -1;
varserv = null;
}
assumeTrue("Did not connect to the variable server", varserv != null);
assumeTrue("Did not find the host name.", !host.isEmpty());
assumeTrue("Did not find the port number", port >= 0);
}
@AfterClass
public static void tearDownAfterClass() {
if(simProc != null && simProc.isAlive())
simProc.destroy();
}
@After
public void cleanup() {
simControl = null;
}
@Override
protected void getCoreActionInfo() { }
@Override
protected void getSupportActionInfo() { }
@Override
protected void getMiscActionInfo() { }
@Test
public void testStartSim() throws IOException {
if (GraphicsEnvironment.isHeadless()) {
headlessStartSim();
} else {
guiStartSim();
}
}
@Test
public void testFreezeSim() throws IOException {
if (GraphicsEnvironment.isHeadless()) {
headlessFreezeSim();
} else {
guiFreezeSim();
}
}
@Test
public void testConnectionFail() {
// ARRANGE
String expOutput = "Invalid TCP/IP port number \"0\"", output;
String badH = "localhost";
int badP = 0;
simControl = new HeadlessSimControlApplication();
System.setErr(new PrintStream(errContent));
// ACT
HeadlessSimControlApplication.setHostPort(badH, badP);
simControl.connect();
sleep(500);
// ASSERT
output = errContent.toString();
assertTrue("Did not recieve the expected error message: \n"
+ output, output.indexOf(expOutput) >= 0);
// CLEAN UP
System.setErr(originalErr);
}
//--------------------//
// GUI Only Tests //
//--------------------//
@Test
/**
* Testing that the freezeAtSim() action functions properly.
*/
public void testFreezeAtTimeSimulation() {
if (GraphicsEnvironment.isHeadless()) {
String testName = "testFreezeAtTimeSimulation";
System.out.println("Testing Headlessly. Skipping '" + testName + "'");
return;
}
// ARRANGE
startApplication(true);
assumeTrue("Sim Control Panel didn't start...", simControl != null);
WaitForSimControlApplication simcontrol = (WaitForSimControlApplication) simControl;
double targetTime = simcontrol.getExecTime() + 3.0;
String statusMsg[], expStatus = "Freeze ON",
expTimeStamp = String.format("%.6f", targetTime);
Matcher line1, line2;
Pattern freezeOffPatt = Pattern.compile("\\|.*\\| Freeze OFF\\.\\n?"),
freezeOnPatt = Pattern.compile("\\|.*\\| Freeze ON\\. Simulation time holding at "
+ expTimeStamp + " seconds\\.\\n?");
// ACT
simcontrol.controller.delayedTypeString((targetTime + "\n"), 500);
simcontrol.freezeAt();
simcontrol.startSim();
simcontrol.sleep(4000);
statusMsg = simcontrol.getStatusMessages().split("\n");
line1 = freezeOffPatt.matcher(statusMsg[0]);
line2 = freezeOnPatt.matcher(statusMsg[1]);
// ASSERT
assumeTrue("Unexpected number of messages", statusMsg.length == 2);
assumeTrue("Simulation did not start!", line1.find());
assertTrue("Simulation didn't freeze at " + expTimeStamp + "\n" + statusMsg[1],
line2.find());
}
@Test
/**
* Testing that the freezeInSim() action functions properly.
*/
public void testFreezeInTimeSimulation() {
if (GraphicsEnvironment.isHeadless()) {
String testName = "testFreezeInTimeSimulation";
System.out.println("Testing Headlessly. Skipping '" + testName + "'");
return;
}
// ARRANGE
startApplication(true);
assumeTrue("Sim Control Panel didn't start...", simControl != null);
WaitForSimControlApplication simcontrol = (WaitForSimControlApplication) simControl;
double targetTime = simcontrol.getExecTime() + 3.0;
String statusMsg[], expStatus = "Freeze ON",
expTimeStamp = String.format("%.6f", targetTime);
Matcher line1, line2;
Pattern freezeOffPatt = Pattern.compile("\\|.*\\| Freeze OFF\\.\\n?"),
freezeOnPatt = Pattern.compile("\\|.*\\| Freeze ON\\. Simulation time holding at "
+ expTimeStamp + " seconds\\.\\n?");
// ACT
simcontrol.controller.delayedTypeString("3.0\n", 500);
simcontrol.freezeIn();
simcontrol.startSim();
simcontrol.sleep(4000);
statusMsg = simcontrol.getStatusMessages().split("\n");
line1 = freezeOffPatt.matcher(statusMsg[0]);
line2 = freezeOnPatt.matcher(statusMsg[1]);
// ASSERT
assumeTrue("Unexpected number of messages", statusMsg.length == 2);
assumeTrue("Simulation did not start!", line1.find());
assertTrue("Simulation didn't freeze at " + expTimeStamp + "\n" + statusMsg[1],
line2.find());
}
@Test
/**
* Testing that the startSim() action functions properly after the
* freezeSim() action.
*/
public void testRestartSimulation() {
if (GraphicsEnvironment.isHeadless()) {
String testName = "testRestartSimulation";
System.out.println("Testing Headlessly. Skipping '" + testName + "'");
return;
}
// ARRANGE
String statusMsg;
String[] statusLines;
Matcher line1, line2, line3;
Pattern freezeOffPatt = Pattern.compile("\\|.*\\| Freeze OFF\\.\\n?"),
freezeOnPatt = Pattern.compile("\\|.*\\| Freeze ON\\. Simulation time holding at \\d+\\.\\d+ seconds\\.\\n?");
int counter = 0;
startApplication(true);
assumeTrue("Sim Control Panel didn't start...", simControl != null);
WaitForSimControlApplication simcontrol = (WaitForSimControlApplication) simControl;
// ACT
simcontrol.startSim();
sleep(1000);
simcontrol.freezeSim();
sleep(1000);
simcontrol.startSim();
do {
counter++;
sleep(500);
statusMsg = simcontrol.getStatusMessages();
statusLines = statusMsg.split("\n");
} while(statusLines.length < 3 && counter < 6);
assumeTrue("Status Message Pane does not have the expected number of entries!", statusLines.length >= 3);
line1 = freezeOffPatt.matcher(statusLines[0]);
line2 = freezeOnPatt.matcher(statusLines[1]);
line3 = freezeOffPatt.matcher(statusLines[2]);
simcontrol.freezeSim();
// ASSERT
assertTrue( "Simulation didn't start correctly:\n" + statusLines[0], line1.find());
assertTrue("Simulation didn't freeze correctly:\n" + statusLines[1], line2.find());
assertTrue("Simulation didn't resume correctly:\n" + statusLines[2], line3.find());
}
@Test
/**
* Testing that the dumpChkpntASCII() action functions properly.
*/
public void testDumpCheckpointSimulation() {
if (GraphicsEnvironment.isHeadless()) {
String testName = "testDumpCheckpointSimulation";
System.out.println("Testing Headlessly. Skipping '" + testName + "'");
return;
}
// ARRANGE
String expMsg = "Dumped ASCII Checkpoint ", actualMsg, errMsg,
fileName, filePath = getTrickHome() + SIM_DIR + "/RUN_test/";
File checkpointFile;
int nameIndex;
startApplication(true);
assumeTrue("Sim Control Panel didn't start...", simControl != null);
WaitForSimControlApplication simcontrol = (WaitForSimControlApplication) simControl;
// ACT
simcontrol.controller.delayedKeyTap(KeyEvent.VK_ENTER, 500);
simcontrol.controller.delayedKeyTap(KeyEvent.VK_ENTER, 750);
simcontrol.dumpChkpntASCII();
sleep(500);
actualMsg = simcontrol.getStatusMessages();
nameIndex = actualMsg.indexOf(expMsg);
assumeTrue("Dumped Checkpoint Message Not Found", nameIndex >= 0);
nameIndex += expMsg.length();
fileName = actualMsg.substring(nameIndex, actualMsg.length() - 2);
checkpointFile = new File(filePath + fileName );
// ASSERT
errMsg = String.format("'%s' Checkpoint File Not Found At '%s'\n", fileName, filePath);
assumeNotNull(errMsg, checkpointFile);
assertTrue(errMsg, checkpointFile.exists());
// CLEANUP
checkpointFile.delete();
}
@Test
/**
* Testing that the loadChkpnt() action functions properly.
*/
public void testLoadCheckpointSimulation() {
if (GraphicsEnvironment.isHeadless()) {
String testName = "testLoadCheckpointSimulation";
System.out.println("Testing Headlessly. Skipping '" + testName + "'");
return;
}
// ARRANGE
String actualMsgs[], fileName = "TESTING_CHECKPOINT_LOAD",
expMsgs[] = {"Load checkpoint file " + getTrickHome() + SIM_DIR + "/RUN_test/TESTING_CHECKPOINT_LOAD.",
"Finished loading checkpoint file. Calling restart jobs.",
"|8.700000| restart variable server message port = " + port};
int counter = 0;
startApplication(true);
assumeTrue("Sim Control Panel didn't start...", simControl != null);
WaitForSimControlApplication simcontrol = (WaitForSimControlApplication) simControl;
// ACT
simcontrol.controller.delayedTypeString(fileName + "\n", 500);
simcontrol.loadChkpnt();
sleep(5000);
actualMsgs = simcontrol.getStatusMessages().split("\n");
assumeTrue("Unexpected Status Messages:\n" + Arrays.toString(actualMsgs), actualMsgs.length >= 3);
// ASSERT
assertTrue("Unexpected Status Message:\n" + actualMsgs[0], actualMsgs[0].endsWith(expMsgs[0]));
assertTrue("Unexpected Status Message:\n" + actualMsgs[1], actualMsgs[1].endsWith(expMsgs[1]));
assertTrue("Unexpected Status Message:\n" + actualMsgs[2], actualMsgs[2].endsWith(expMsgs[2]));
}
@Test
/**
* Testing that data recording toggles off and on correctly.
*/
public void testDataRecordingToggle() {
if (GraphicsEnvironment.isHeadless()) {
String testName = "testDataRecordingToggle";
System.out.println("Testing Headlessly. Skipping '" + testName + "'");
return;
}
// ARRANGE
final boolean expectedOrder[] = {true, false, true};
boolean actualOrder[] = new boolean[3];
startApplication(true);
assumeTrue("Sim Control Panel didn't start...", simControl != null);
WaitForSimControlApplication simcontrol = (WaitForSimControlApplication) simControl;
// ACT
for(int i = 0; i < actualOrder.length; i++) {
actualOrder[i] = simcontrol.isDataRecOn();
simcontrol.toggleDataRecButton();
sleep(1000);
}
// ASSERT
assertTrue("Data Recording was not ON at the start of the Sim",
expectedOrder[0] == actualOrder[0]);
assertTrue("Data Recording didn't toggle OFF correctly",
expectedOrder[1] == actualOrder[1]);
assertTrue("Data Recording didn't toggle back ON correctly",
expectedOrder[2] == actualOrder[2]);
}
@Test
/**
* Testing that data recording toggles off and on correctly.
*/
public void testRealTimeToggle() {
if (GraphicsEnvironment.isHeadless()) {
String testName = "testRealTimeToggle";
System.out.println("Testing Headlessly. Skipping '" + testName + "'");
return;
}
// ARRANGE
final boolean expectedOrder[] = {true, false, true};
boolean actualOrder[] = new boolean[3];
startApplication(true);
assumeTrue("Sim Control Panel didn't start...", simControl != null);
WaitForSimControlApplication simcontrol = (WaitForSimControlApplication) simControl;
// ACT
actualOrder[0] = simcontrol.isRealTimeOn(); // Expected TRUE
actualOrder[1] = toggleRealTime(simcontrol); // Expected FALSE
actualOrder[2] = toggleRealTime(simcontrol); // Expected TRUE
// ASSERT
assertTrue("Real Time was not ON at the start of the Sim",
expectedOrder[0] == actualOrder[0]);
assertTrue("Real Time didn't toggle OFF correctly",
expectedOrder[1] == actualOrder[1]);
assertTrue("Real Time didn't toggle back ON correctly",
expectedOrder[2] == actualOrder[2]);
}
// Hybrid Test helper methods
private boolean toggleRealTime(WaitForSimControlApplication app) {
app.toggleRealTimeButton();
sleep(1000);
return app.isRealTimeOn();
}
private void headlessStartSim() throws IOException {
// ARRANGE
String out;
int mode = 1, count = 0;
simControl = new HeadlessSimControlApplication(host, port);
sleep(1000);
simControl.connect();
sleep(1000);
// ACT
varserv.put("trick.var_send_once(\"trick_sys.sched.mode\")");
mode = Integer.parseInt(varserv.get().split("\t")[1]);
assumeTrue("Sim Mode was not MODE_FREEZE at test start", mode == MODE_FREEZE);
simControl.startSim();
do {
count ++;
varserv.put("trick.var_send_once(\"trick_sys.sched.mode\")");
mode = Integer.parseInt(varserv.get().split("\t")[1]);
} while (mode != 5 && count < 100000);
// ASSERT
assertTrue("Sim Mode is not MODE_RUN(5)\nMODE_ID=" + mode, mode == MODE_RUN);
// CLEAN UP
varserv.put("trick.exec_freeze()\n");
}
private void guiStartSim() throws IOException {
// ARRANGE
String statusMsg, expStatus = "Freeze OFF";
int counter = 0;
startApplication(true);
assumeTrue("Sim Control Panel didn't start...", simControl != null);
WaitForSimControlApplication guiControl = (WaitForSimControlApplication) simControl;
// ACT
varserv.put("trick.var_send_once(\"trick_sys.sched.mode\")");
int mode = Integer.parseInt(varserv.get().split("\t")[1]);
assumeTrue("Sim Mode was not MODE_FREEZE at test start", mode == MODE_FREEZE);
guiControl.clearStatusMsgs();
guiControl.startSim();
do {
counter++;
sleep(500);
statusMsg = guiControl.getStatusMessages();
} while(statusMsg.isEmpty() && counter < 5);
guiControl.freezeSim();
// ASSERT
assertTrue("Simulation did not start!\n" + statusMsg, statusMsg.indexOf(expStatus) != -1);
}
private void headlessFreezeSim() throws IOException {
// ARRANGE
String out;
int mode = 1, count = 0;
simControl = new HeadlessSimControlApplication(host, port);
sleep(1000);
simControl.connect();
sleep(1000);
simControl.startSim();
sleep(1000);
varserv.put("trick.var_send_once(\"trick_sys.sched.mode\")");
mode = Integer.parseInt(varserv.get().split("\t")[1]);
assumeTrue("Sim Mode was not MODE_RUN at test start", mode == MODE_RUN);
// ACT
simControl.freezeSim();
do {
count ++;
varserv.put("trick.var_send_once(\"trick_sys.sched.mode\")");
mode = Integer.parseInt(varserv.get().split("\t")[1]);
} while (mode != 1 && count < 100000);
// ASSERT
assertTrue("Sim Mode is not MODE_FREEZE (1)\nMODE_ID=" + mode, mode == MODE_FREEZE);
}
private void guiFreezeSim() throws IOException {
// ARRANGE
String statusMsg, expStatus = "Freeze ON";
int counter = 0;
startApplication(true);
assumeTrue("Sim Control Panel didn't start...", simControl != null);
WaitForSimControlApplication guiControl = (WaitForSimControlApplication) simControl;
// ACT
guiControl.startSim();
guiControl.freezeSim();
do {
counter++;
sleep(500);
statusMsg = guiControl.getStatusMessages();
} while(statusMsg.indexOf(expStatus) < 0 && counter < 5);
// ASSERT
assertTrue("Simulation did not freeze!\n" + statusMsg, statusMsg.indexOf(expStatus) != -1);
}
private static void startApplication(boolean startConnected) {
if(simControl == null) {
if(startConnected) // Launch Testing SimControlPanel with the provided connection info
WaitForSimControlApplication.launchAndWait(WaitForSimControlApplication.class, host, port);
else // Launch Testing SimControlPanel
WaitForSimControlApplication.launchAndWait(WaitForSimControlApplication.class);
handleAppSetup();
} else {
System.err.println("SimControlApplication is already Running...");
}
}
private static void handleAppSetup() {
// Set up the required variables for testing
simControl = Application.getInstance(WaitForSimControlApplication.class);
// Ensure that everything got set up correctly.
assumeTrue("SimControlApplicationTest is not ready yet!", simControl.isReady());
}
}

View File

@ -1,5 +1,6 @@
package trick.simcontrol;
import trick.common.ApplicationTest;
import trick.common.fixtures.FontChooserFixture;
import trick.common.ui.components.FontChooser;
import trick.simcontrol.SimControlApplication;
@ -8,12 +9,13 @@ import trick.simcontrol.StubbedSimControlApplication;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.Dimension;
import java.awt.event.KeyEvent;
import java.awt.GraphicsEnvironment;
import java.awt.Toolkit;
import java.beans.Transient;
import java.util.ArrayList;
@ -54,8 +56,7 @@ import static org.assertj.core.api.Assumptions.assumeThat;
import static org.assertj.swing.finder.WindowFinder.findFrame;
import static org.assertj.swing.launcher.ApplicationLauncher.application;
public class StubbedSimControlTests extends AssertJSwingJUnitTestCase {
private FrameFixture mainFrame;
public class SimControlApplicationTests extends ApplicationTest {
private JPanelFixture findPanel;
private JTextComponentFixture editorFixture;
private JToolBarFixture toolBarFixture;
@ -94,7 +95,6 @@ public class StubbedSimControlTests extends AssertJSwingJUnitTestCase {
toolBarFixture = mainFrame.toolBar();
sleep(500);
updateState();
}
//--------------------
@ -261,10 +261,13 @@ public class StubbedSimControlTests extends AssertJSwingJUnitTestCase {
FontChooserFixture fontDialogFixt;
JButtonFixture okButton;
JMenuItemFixture fontMenu = getJMenuItemByName(mainFrame, "showStatusFontMenuItem");
JMenuItemFixture fontMenu = mainFrame.menuItem("showStatusFontMenuItem");
final String[] fonts = GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames();
assumeThat(fonts.length > 0).withFailMessage("No Available Fonts Installed...\n").isTrue();
final int fontSize = 15;
final String fontName = "Droid Sans",
final String fontName = fonts[(int)(fonts.length / 2)],
expPreviewText = fontName + ":3:" + fontSize;
final Font expFont = new Font(fontName, 3, fontSize);
@ -300,7 +303,7 @@ public class StubbedSimControlTests extends AssertJSwingJUnitTestCase {
public void testSaveStatusMessage() {
// ARRANGE
ActionID action;
JMenuItemFixture saveMsg = getJMenuItemByName(mainFrame, "saveStatusMsgsMenuItem");
JMenuItemFixture saveMsg = mainFrame.menuItem("saveStatusMsgsMenuItem");
assumeThat(saveMsg).isNotNull();
@ -316,7 +319,7 @@ public class StubbedSimControlTests extends AssertJSwingJUnitTestCase {
public void testClearStatusMessage() {
// ARRANGE
ActionID action;
JMenuItemFixture clearMsg = getJMenuItemByName(mainFrame, "clearStatusMsgsMenuItem");
JMenuItemFixture clearMsg = mainFrame.menuItem("clearStatusMsgsMenuItem");
editorFixture.enterText("MOOSE MOOSE MOOSE");
@ -335,7 +338,7 @@ public class StubbedSimControlTests extends AssertJSwingJUnitTestCase {
/* Not sure if I should test each of the LookAndFeel buttons */
public void testLookAndFeel() {
// ARRANGE
JMenuItemFixture lafItem = getJMenuItemByName(mainFrame, "lookAndFeelMenuItem");
JMenuItemFixture lafItem = mainFrame.menuItem("lookAndFeelMenuItem");
UIManager.LookAndFeelInfo looks[] = UIManager.getInstalledLookAndFeels();
assumeThat(looks.length > 0).withFailMessage("No LookAndFeel is installed...\n").isTrue();
@ -367,7 +370,7 @@ public class StubbedSimControlTests extends AssertJSwingJUnitTestCase {
@Test
public void testStartTrickViewMenuItem() {
// ARRANGE
final JMenuItemFixture TV_ITEM = getJMenuItemByName(mainFrame, "startTVMenuItem");
final JMenuItemFixture TV_ITEM = mainFrame.menuItem("startTVMenuItem");
final ActionID TV_ACTION = ActionID.TV;
ActionID loggedAction;
@ -383,7 +386,7 @@ public class StubbedSimControlTests extends AssertJSwingJUnitTestCase {
@Test
public void testStartMalfunctionTrickViewMenuItem() {
// ARRANGE
final JMenuItemFixture MTV_ITEM = getJMenuItemByName(mainFrame, "startMTVMenuItem");
final JMenuItemFixture MTV_ITEM = mainFrame.menuItem("startMTVMenuItem");
final ActionID MTV_ACTION = ActionID.MTV;
ActionID loggedAction;
@ -399,7 +402,7 @@ public class StubbedSimControlTests extends AssertJSwingJUnitTestCase {
@Test
public void testFreezeAtMenuItem() {
// ARRANGE
final JMenuItemFixture FREEZE_AT_ITEM = getJMenuItemByName(mainFrame, "freezeAtMenuItem");
final JMenuItemFixture FREEZE_AT_ITEM = mainFrame.menuItem("freezeAtMenuItem");
final ActionID FREEZE_AT_ACTION = ActionID.FREEZE_AT;
ActionID loggedAction;
@ -415,7 +418,7 @@ public class StubbedSimControlTests extends AssertJSwingJUnitTestCase {
@Test
public void testFreezeInMenuItem() {
// ARRANGE
final JMenuItemFixture FREEZE_IN_ITEM = getJMenuItemByName(mainFrame, "freezeInMenuItem");
final JMenuItemFixture FREEZE_IN_ITEM = mainFrame.menuItem("freezeInMenuItem");
final ActionID FREEZE_IN_ACTION = ActionID.FREEZE_IN;
ActionID loggedAction;
@ -432,7 +435,7 @@ public class StubbedSimControlTests extends AssertJSwingJUnitTestCase {
@Test
public void testCheckpointMenuItem() {
// ARRANGE
final JMenuItemFixture CHKPNT_OBJ_ITEM = getJMenuItemByName(mainFrame, "checkpointObjectsMenuItem");
final JMenuItemFixture CHKPNT_OBJ_ITEM = mainFrame.menuItem("checkpointObjectsMenuItem");
final ActionID CHKPNT_OBJ_ACTION = ActionID.PART_CHKPNT;
ActionID loggedAction;
@ -448,7 +451,7 @@ public class StubbedSimControlTests extends AssertJSwingJUnitTestCase {
@Test
public void testThrottleMenuItem() {
// ARRANGE
final JMenuItemFixture THROTTLE_ITEM = getJMenuItemByName(mainFrame, "throttleMenuItem");
final JMenuItemFixture THROTTLE_ITEM = mainFrame.menuItem("throttleMenuItem");
final ActionID THROTTLE_ACTION = ActionID.THROTTLE;
ActionID loggedAction;
@ -493,10 +496,6 @@ public class StubbedSimControlTests extends AssertJSwingJUnitTestCase {
// Helper Methods
//--------------------
public static void sleep(long ms) {
try {Thread.sleep(ms);} catch(Exception ignored) {}
}
private void setStatusMessage(String text) {
editorFixture.deleteText()
.setText(text);
@ -515,10 +514,25 @@ public class StubbedSimControlTests extends AssertJSwingJUnitTestCase {
try {
findTextField.deleteText()
.setText(text);
} catch(Exception ignored) {}
} catch(Exception skipTest) {
assumeThat(false).withFailMessage("Error with JXFindBar Implementation\n").isTrue();
}
}
protected FontChooserFixture getFontChooserFixture() {
try {
AbstractComponentFixture abst = mainFrame.with(FontChooserFixture.getExtension());
if (abst instanceof FontChooserFixture)
return (FontChooserFixture) abst;
else
return null;
} catch(Exception e) {
return null;
}
}
private void testJButton(String text, ActionID action) {
JButtonFixture button = getButtonByText(text);
assumeThat(button).withFailMessage("Button with text\"%s\" not found\n", text)
@ -527,57 +541,6 @@ public class StubbedSimControlTests extends AssertJSwingJUnitTestCase {
testConnectedAction(button, action);
}
private void updateState() {
JToggleButtonFixture liteFixture, recordFixture, realFixture;
liteFixture = getToggleButtonByText("Lite");
if (liteFixture == null)
liteFixture = getToggleButtonByText("Full");
}
private void testButtonToggleOnce(String text, ActionID action) { testButtonToggleOnce(text, text, action); }
private void testButtonToggleOnce(String initText, String toggleText, ActionID initAction) {
// ARRANGE
JToggleButtonFixture button = getToggleButtonByText(initText);
String newButtonText;
assumeThat(button).withFailMessage("Toggle Button with text\"%s\" not found\n", initText)
.isNotNull();
// ACT
testConnectedAction(button, initAction); // Toggle
newButtonText = button.target().getText();
// ASSERT
assertThat(newButtonText).isEqualTo(toggleText);
}
private void testButtonToggleTwice(String text, ActionID action) { testButtonToggleTwice(text, action, text, action); }
private void testButtonToggleTwice(String initText, String toggleText, ActionID action) {
testButtonToggleTwice(initText, action, toggleText, action);
}
private void testButtonToggleTwice(String initText, ActionID initAction, String toggleText, ActionID toggleAction) {
// ARRANGE
JToggleButtonFixture button = getToggleButtonByText(initText);
String buttonText, newButtonText;
assumeThat(button).withFailMessage("Toggle Button with text\"%s\" not found\n", initText)
.isNotNull();
// ACT
testConnectedAction(button, initAction); // Toggle On
newButtonText = button.target().getText();
testConnectedAction(button, toggleAction); // Toggle Off
buttonText = button.target().getText();
// ASSERT
assertThat(newButtonText).isEqualTo(toggleText);
assertThat(buttonText).isEqualTo(initText);
}
private void testConnectedAction(MouseInputSimulationFixture clickable, ActionID expected) {
// ARRANGE
ActionID actual;
@ -598,104 +561,45 @@ public class StubbedSimControlTests extends AssertJSwingJUnitTestCase {
assertThat(logSize).isEqualTo(initialLogSize + 1);
}
protected FontChooserFixture getFontChooserFixture() {
try {
AbstractComponentFixture abst = mainFrame.with(FontChooserFixture.getExtension());
private void testButtonToggleOnce(String initText, String toggleText, ActionID initAction) {
// ARRANGE
JToggleButtonFixture button = getToggleButtonByText(initText);
String newButtonText;
assumeThat(button).withFailMessage("Toggle Button with text\"%s\" not found\n", initText)
.isNotNull();
if (abst instanceof FontChooserFixture)
return (FontChooserFixture) abst;
else
return null;
} catch(Exception e) {
return null;
}
// ACT
testConnectedAction(button, initAction); // Toggle
newButtonText = button.target().getText();
// ASSERT
assertThat(newButtonText).isEqualTo(toggleText);
}
protected FrameFixture getFrameByTitle(String title) {
FrameFixture frame = findFrame(new GenericTypeMatcher<Frame>(Frame.class) {
protected boolean isMatching(Frame frame) {
return title.equals(frame.getTitle()) && frame.isShowing();
}
}).using(robot());
private void testButtonToggleOnce(String text, ActionID action) { testButtonToggleOnce(text, text, action); }
return frame;
private void testButtonToggleTwice(String initText, ActionID initAction, String toggleText, ActionID toggleAction) {
// ARRANGE
JToggleButtonFixture button = getToggleButtonByText(initText);
String buttonText, newButtonText;
assumeThat(button).withFailMessage("Toggle Button with text\"%s\" not found\n", initText)
.isNotNull();
// ACT
testConnectedAction(button, initAction); // Toggle On
newButtonText = button.target().getText();
testConnectedAction(button, toggleAction); // Toggle Off
buttonText = button.target().getText();
// ASSERT
assertThat(newButtonText).isEqualTo(toggleText);
assertThat(buttonText).isEqualTo(initText);
}
protected JMenuItemFixture getJMenuByName(ComponentContainerFixture container, String name) {
JMenuItemFixture menu;
private void testButtonToggleTwice(String text, ActionID action) { testButtonToggleTwice(text, action, text, action); }
try {
menu = container.menuItem(new GenericTypeMatcher<JMenu>(JMenu.class) {
@Override
protected boolean isMatching(JMenu jmenu) {
return name.equals(jmenu.getName());
}
});
} catch (ComponentLookupException e) {
return null;
}
return menu;
}
protected JMenuItemFixture getJMenuItemByName(ComponentContainerFixture container, String name) {
JMenuItemFixture menu;
try {
menu = container.menuItem(new GenericTypeMatcher<JMenuItem>(JMenuItem.class) {
@Override
protected boolean isMatching(JMenuItem jmenu) {
return name.equals(jmenu.getName());
}
});
} catch (ComponentLookupException e) {
return null;
}
return menu;
}
protected JButtonFixture getButtonByText(ComponentContainerFixture container, String text) {
JButtonFixture button;
try {
button = container.button(new GenericTypeMatcher<JButton>(JButton.class) {
@Override
protected boolean isMatching(JButton button) {
return text.equals(button.getText());
}
});
} catch (ComponentLookupException e) {
return null;
}
return button;
}
protected JToggleButtonFixture getToggleButtonByText(String text) {
return getToggleButtonByText(mainFrame, text);
}
protected JToggleButtonFixture getToggleButtonByText(ComponentContainerFixture container, String text) {
JToggleButtonFixture button;
try {
button = container.toggleButton(new GenericTypeMatcher<JToggleButton>(JToggleButton.class) {
@Override
protected boolean isMatching(JToggleButton button) {
return text.equals(button.getText());
}
});
} catch (ComponentLookupException e) {
return null;
}
return button;
}
protected JButtonFixture getButtonByText(String text) {
return getButtonByText(mainFrame, text);
private void testButtonToggleTwice(String initText, String toggleText, ActionID action) {
testButtonToggleTwice(initText, action, toggleText, action);
}
}

View File

@ -1,138 +0,0 @@
package trick.simcontrol;
import javax.swing.JFrame;
import javax.swing.JComboBox;
import javax.swing.JEditorPane;
import javax.swing.JTextField;
import javax.swing.JToggleButton;
import javax.swing.text.Document;
import java.awt.AWTException;
import java.awt.Component;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.awt.event.WindowEvent;
import org.jdesktop.application.Application;
import org.jdesktop.swingx.JXEditorPane;
import trick.common.GUIController;
import trick.simcontrol.SimControlApplication;
public class WaitForSimControlApplication extends SimControlApplication {
static Object lock = new Object();
boolean isEnded;
public GUIController controller;
public WaitForSimControlApplication() throws AWTException{
super();
controller = new GUIController();
// controller.setAutoDelay(250);
}
public void sleep(long ms) {
try { Thread.sleep(ms); } catch (Exception ignored) { }
}
@Override
protected void end() {
isEnded = true;
}
@Override
protected void ready() {
super.ready();
synchronized(lock) {
lock.notifyAll();
}
}
public static void launchAndWait(Class<? extends WaitForSimControlApplication> applicationClass, String host, int port) {
setHostPort(host, port);
launchAndWait(applicationClass);
}
/**
* Launch the specified subclsas of SimControlApplication and block
* (wait) until it's startup() method has run.
*/
public static void launchAndWait(Class<? extends WaitForSimControlApplication> applicationClass) {
synchronized(lock) {
Application.launch(applicationClass, new String[]{});
while(true) {
try {
lock.wait();
}
catch (InterruptedException e) {
System.err.println("launchAndWait interrupted!");
break;
}
Application app = Application.getInstance(WaitForSimControlApplication.class);
if (app instanceof WaitForSimControlApplication) {
if (((WaitForSimControlApplication)app).isReady()) {
break;
}
}
}
}
}
//========================================
// Robot Methods
//========================================
public void editRunningSimList(String socketInfo) {
getRunningSimList().setSelectedItem(socketInfo);
}
public void toggleDataRecButton() {
JToggleButton button = getDataRecButton();
selectComponent(button);
}
public void toggleRealTimeButton() {
JToggleButton button = getRealTimeButton();
selectComponent(button);
}
private void selectAndClearField(Component field) {
selectComponent(field);
controller.clearTextField();
controller.waitForIdle();
}
private void selectComponent(Component comp) {
controller.mouseClickAt(InputEvent.BUTTON1_DOWN_MASK, comp);
controller.waitForIdle();
}
//========================================
// Getter Methods
//========================================
public String getRunningSimInfo() {
JTextField runDir = getSimRunDirField();
if (runDir == null) {
return "";
}
return runDir.getText();
}
public String getStatusMessages() {
JXEditorPane status = getEditorPane();
String msg = "";
try {
Document doc = status.getDocument();
msg = doc.getText(0, doc.getLength());
} catch (Exception e) {
msg = e.getMessage();
}
return msg;
}
public boolean isDataRecOn() { return getDataRecButton().isSelected(); }
public boolean isRealTimeOn() { return getRealTimeButton().isSelected(); }
}