source: tmcsimulator/trunk/test/tmcsim/cadsimulator/CADSimulatorConsoleTest.java @ 655

Revision 655, 22.9 KB checked in by jdalbey, 4 years ago (diff)

Improve unit tests.

Line 
1package tmcsim.cadsimulator;
2
3import java.io.File;
4import java.io.FileWriter;
5import java.io.IOException;
6import java.io.PrintWriter;
7import java.io.StringWriter;
8import java.util.logging.Level;
9import java.util.logging.Logger;
10import junit.framework.TestCase;
11import org.apache.commons.lang.StringUtils;
12import static org.mockito.Mockito.mock;
13import tmcsim.cadsimulator.viewer.CADConsoleViewer;
14import tmcsim.common.CADEnums;
15import tmcsim.common.ScriptException;
16import tmcsim.common.SimulationException;
17import tmcsim.interfaces.CADClientInterface;
18import tmcsim.interfaces.SimulationManagerInterface;
19import static tmcsim.simulationmanager.SimulationManager.kScenarioFolder;
20
21/**
22 * Test of CADSimulator Console
23 *
24 * @author jdalbey
25 */
26public class CADSimulatorConsoleTest extends TestCase
27{
28
29    private static CADServer app = null;
30    private CADConsoleViewer console;
31    private StringWriter sw;
32    // Setup a path for temp files
33    static String tmpPath = "/tmp/";// default path is for linux
34    static
35    {
36        String myOs = System.getProperty("os.name").toLowerCase();
37        if (myOs.indexOf("win") >= 0) 
38        {
39          tmpPath = "C:/TEMP/";  // alt path for Windows
40        }
41    }
42    public CADSimulatorConsoleTest(String testName)
43    {
44        super(testName);
45    }
46
47    public void setUp() throws Exception
48    {
49        super.setUp();
50        writeConfigData();
51        // Since CADSimulator has registry, we musn't instantiate it more than once
52        if (app == null)
53        {
54            try
55            {
56                app = new CADServer("config.txt");
57            } catch (Exception ex)
58            {
59                fail("Couldn't launch CADSimulator");
60            }
61        }
62        console = (CADConsoleViewer) app.theViewer;
63        sw = new StringWriter();
64        console.setWriter(sw);
65    }
66
67    @Override
68    public void tearDown() throws java.io.IOException
69    {
70        File removeMe = new File("config.txt");
71        removeMe.delete();
72        removeMe = new File("pconfig.txt");
73        removeMe.delete();
74        removeMe = new File("tconfig.txt");
75        removeMe.delete();
76        removeMe = new File("empty.txt");
77        removeMe.delete();
78    }
79
80    /**
81     * obsolete: compare StringWriter contents against expected
82     */
83    private void verify0(String msg, String expect)
84    {
85        String result = sw.toString().trim();
86        System.out.println(""+result);
87        result = result.replaceAll("\n", ",");
88        String fullExpect = expect.trim();
89        fullExpect = fullExpect.replaceAll("\n", ",");
90//        System.out.println(fullExpect);
91        System.out.println(result.substring(result.length() - fullExpect.length(), result.length()));
92//        String diff = StringUtils.difference(fullExpect, result);
93        boolean match = result.endsWith(fullExpect);
94        assertTrue(msg + ": " + result, match);
95    }
96    /** compare StringWriter contents against expected
97     *  @param expected contains just the most recent lines of output
98     *  @param errmsg message to be displayed if test fails
99     *  improved to verify line by line
100     */
101    private void verify(String errmsg, String expect)
102    {
103        String[] results = sw.toString().trim().split("\n");   // split into lines
104        String[] expecteds = expect.trim().split("\n");
105        // Work backwards from the most recent line of output
106        for (int item=expecteds.length-1; item >= 0; item--)
107        {
108            //System.out.println("Verifying "+expecteds[item]+" against "+results[item]);
109            assertEquals(errmsg + " line "+item, expecteds[item], results[item]);
110        }   
111    }           
112    public static void pause(int millis)
113    {
114        try
115        {
116            Thread.sleep(millis);
117        } catch (InterruptedException ex)
118        {
119        }
120    }
121
122    /**
123     * The tests must be all run in one method, because the order matters. As
124     * separate methods, we couldn't control which is executed first.
125     *
126     * @throws java.io.IOException
127     * @throws SimulationException
128     * @throws ScriptException
129     */
130    public void testAll() throws java.io.IOException, SimulationException, ScriptException
131    {
132        CADConsoleViewer console = (CADConsoleViewer) app.theViewer;
133        String expected1 =
134                "--- CAD Simulator ---\n"
135                + "Elapsed Simulation Time     : 0:00:00\n"
136                + "Status                      : No Script\n"
137                + "Connected CAD Terminals     : 0\n"
138                + "Simulation Manager Connected: No\n"
139                + "Connected to Paramics       : No\n"
140                + "Network Loaded              : None\n"
141                + "-- Info Messages --\n\n"
142                + "-- Error Messages --";
143        System.out.println("setVisible");
144        console.setVisible(true);
145        verify("Initial output incorrect: ", expected1);
146        String expected2 =
147                "--- CAD Simulator ---\n"
148                + "Elapsed Simulation Time     : 0:00:00\n"
149                + "Status                      : No Script\n"
150                + "Connected CAD Terminals     : 1\n"
151                + "Simulation Manager Connected: No\n"
152                + "Connected to Paramics       : No\n"
153                + "Network Loaded              : None\n"
154                + "-- Info Messages --\n\n"
155                + "-- Error Messages --\n\n";
156
157        System.out.println("connect one");
158        CADClientInterface ci = mock(CADClientInterface.class);
159        app.theCoordinator.registerForCallback(ci);
160        pause(500);
161        verify("connected 1 terminal output incorrect: ", expected2);
162        String expected3 =
163                "--- CAD Simulator ---\n"
164                + "Elapsed Simulation Time     : 0:00:00\n"
165                + "Status                      : No Script\n"
166                + "Connected CAD Terminals     : 2\n"
167                + "Simulation Manager Connected: No\n"
168                + "Connected to Paramics       : No\n"
169                + "Network Loaded              : None\n"
170                + "-- Info Messages --\n\n"
171                + "-- Error Messages --\n\n";
172        System.out.println("connect two");
173        app.theCoordinator.registerForCallback(ci);
174        verify("connected 2 terminals output incorrect: ", expected3);
175        System.out.println("disconnect");
176        app.theCoordinator.unregisterForCallback(ci);
177        verify("disconnect terminal output incorrect: ", expected2);
178        app.theCoordinator.unregisterForCallback(ci);
179        String expected4 =
180                "--- CAD Simulator ---\n"
181                + "Elapsed Simulation Time     : 0:00:00\n"
182                + "Status                      : No Script\n"
183                + "Connected CAD Terminals     : 0\n"
184                + "Simulation Manager Connected: Yes\n"
185                + "Connected to Paramics       : No\n"
186                + "Network Loaded              : None\n"
187                + "-- Info Messages --\n\n"
188                + "-- Error Messages --\n\n";
189        System.out.println("sim mgr connect");
190        SimulationManagerInterface si = mock(SimulationManagerInterface.class);
191        app.theCoordinator.registerForCallback(si);
192        verify("sim mgr connected output incorrect: ", expected4);
193        String expected5 =
194                "--- CAD Simulator ---\n"
195                + "Elapsed Simulation Time     : 0:00:00\n"
196                + "Status                      : No Script\n"
197                + "Connected CAD Terminals     : 0\n"
198                + "Simulation Manager Connected: Yes\n"
199                + "Connected to Paramics       : No\n"
200                + "Network Loaded              : None\n"
201                + "-- Info Messages --\n"
202                + ". = Console Info Message.\n"
203                + "-- Error Messages --\n\n";
204        System.out.println("Info msg");
205        Logger cadSimLogger = Logger.getLogger("tmcsim.cadsimulator");
206        cadSimLogger.logp(Level.INFO, "", "", "Console Info Message.");
207        verify("Info message output incorrect: ", expected5);
208        String expected7 =
209                "--- CAD Simulator ---\n"
210                + "Elapsed Simulation Time     : 0:00:00\n"
211                + "Status                      : No Script\n"
212                + "Connected CAD Terminals     : 0\n"
213                + "Simulation Manager Connected: Yes\n"
214                + "Connected to Paramics       : No\n"
215                + "Network Loaded              : None\n"
216                + "-- Info Messages --\n"
217                + ". = Console Info Message.\n"
218                + "-- Error Messages --\n"
219                + "Someclass.Somemethod = Sample error message.\n";
220        System.out.println("Error msg");
221        cadSimLogger = Logger.getLogger("tmcsim.cadsimulator");
222        cadSimLogger.logp(Level.SEVERE, "Someclass", "Somemethod", "Sample error message.");
223        verify("Error message output incorrect: ", expected7);
224        String expected6 =
225                "--- CAD Simulator ---\n"
226                + "Elapsed Simulation Time     : 0:00:00\n"
227                + "Status                      : No Script\n"
228                + "Connected CAD Terminals     : 0\n"
229                + "Simulation Manager Connected: Yes\n"
230                + "Connected to Paramics       : Yes\n"
231                + "Network Loaded              : None\n"
232                + "-- Info Messages --\n"
233                + ". = Console Info Message.\n"
234                + "-- Error Messages --\n"
235                + "Someclass.Somemethod = Sample error message.\n";
236        System.out.println("Paramics connect");
237        app.theCoordinator.setParamicsStatus(CADEnums.PARAMICS_STATUS.CONNECTED);
238        pause(500);
239        pause(500);
240        verify("paramics connected should be yes", expected6);
241        String expected8 =
242                "--- CAD Simulator ---\n"
243                + "Elapsed Simulation Time     : 0:00:00\n"
244                + "Status                      : Ready\n"
245                + "Connected CAD Terminals     : 0\n"
246                + "Simulation Manager Connected: Yes\n"
247                + "Connected to Paramics       : Yes\n"
248                + "Network Loaded              : None\n"
249                + "-- Info Messages --\n"
250                + ". = Console Info Message."
251                + "tmcsim.cadsimulator.Coordinator.copyXMLfile = Loaded script copied to webapps/dynamicdata/incident_script.xml\n"
252                + "-- Error Messages --\n"
253                + "Someclass.Somemethod = Sample error message.\n";
254        String expected9 =
255                "--- CAD Simulator ---\n"
256                + "Elapsed Simulation Time     : 0:00:01\n"
257                + "Status                      : Running\n"
258                + "Connected CAD Terminals     : 0\n"
259                + "Simulation Manager Connected: Yes\n"
260                + "Connected to Paramics       : Yes\n"
261                + "Network Loaded              : None\n"
262                + "-- Info Messages --\n"
263                + ". = Console Info Message."
264                + "tmcsim.cadsimulator.Coordinator.copyXMLfile = Loaded script copied to webapps/dynamicdata/incident_script.xml\n"
265                + "-- Error Messages --\n"
266                + "Someclass.Somemethod = Sample error message.\n";
267        System.out.println("Sim status");
268        // Load a script file - to put status at Ready
269        String autoloadScriptname = kScenarioFolder+"/one-incident.xml";
270        app.theCoordinator.loadScriptFile(new File(autoloadScriptname));
271        pause(2000);
272        verify("Status should be 'ready'", expected8);
273        // startSimulation to put status at Running
274        app.theCoordinator.startSimulation();
275        pause(500);
276        verify("Status should be 'running', time should be 0:01", expected9);
277    }
278//    public void testNetworkID()
279//    {
280//        String expected10 =
281//                "--- CAD Simulator ---\n"
282//                + "Elapsed Simulation Time     : 0:00:00\n"
283//                + "Status                      : No Script\n"
284//                + "Connected CAD Terminals     : 0\n"
285//                + "Simulation Manager Connected: No\n"
286//                + "Connected to Paramics       : No\n"
287//                + "Network Loaded              : 17\n"
288//                + "-- Info Messages --\n\n"
289//                + "-- Error Messages --\n\n";
290//        // this will tell the model it has a new network ID
291//        cadmodel.setParamicsNetworkLoaded("17");
292//        cadmodel.setParamicsStatus(CADEnums.PARAMICS_STATUS.LOADED);
293//        pause(500);
294//        verify("network id should be 17", expected10);
295//    }
296//    ByteArrayOutputStream bos;
297//    PrintStream ps;
298    static final String configData =
299            "CADClientPort          = 4444 \n"
300            + "CoordinatorRMIPort     = 4445 \n"
301            + "CADRmiPort             = 4446 \n"
302            + "UserInterface          = tmcsim.cadsimulator.viewer.CADConsoleViewer\n"
303            + "ParamicsProperties     = pconfig.txt\n"
304            + "ATMSProperties         = empty.txt\n"
305            + "TrafficMgrProperties   = tconfig.txt\n"
306            + "MediaProperties        = empty.txt\n"
307            + "ElapsedTimeFile        = webapps/dynamicdata/sim_elapsedtime.json\n"
308            + "CADcommentsLog         = CADcomments.log";
309    static final String trafficMgrData = "Highways_Map_File = config/vds_data/postmile_coordinates.txt\n"
310            +"Events_File = config/vds_data/atmsBatchEvents.txt\n"
311            +"FEPSim_IP_addr = localhost\n"
312            +"Output_Destination = Console\n"
313            +"Highway_Status_File = "+tmpPath+"highway_status.json\n";
314    static final String paramicsData = "ParamicsCommHost = 127.0.0.1\n"
315            + "ParamicsCommPort       = 4450\n"
316            + "IncidentUpdateInterval = 30\n"
317            + "IncidentUpdateFile     = exchange.xml\n"
318            + "ParamicsStatusInterval = 15\n"
319            + "ParamicsStatusFile     = paramics_status.xml\n"
320            + "CameraStatusInterval   = 30\n"
321            + "CameraStatusFile       = camera_status.xml\n";
322    static final String cardfileURL = "http://pastebin.com/raw/Yr26nfp7";
323    static final String smallXMLURL = "http://pastebin.com/raw/Eqj2N5qD";
324    /*
325     * Creating instance of app must be done only once or you get registry
326     * bind problems, and code Written in Constructor is Executed
327     * before each Test Method
328     */
329
330    private void writeConfigData()
331    {
332        // Declare a stream to the output
333//        bos = new ByteArrayOutputStream();
334//        ps = new PrintStream(bos);
335        // Redirect the standard output
336//        System.setOut(ps);
337        File cf = new File ("config.txt");
338        cf.delete();
339        writedata("config.txt", configData);
340        File tf = new File ("tconfig.txt");
341        tf.delete();
342        writedata("tconfig.txt", trafficMgrData);
343        writedata("pconfig.txt", paramicsData);
344        writedata("empty.txt", "");
345        writeScriptfiles();
346    }
347
348    private void writeScriptfiles()
349    {
350        new File("scripts").mkdir();
351        writedata(kScenarioFolder+"/Cardfile.xml", cardfileData);
352        writedata(kScenarioFolder+"/one-incident.xml", oneincidentXML);
353    }
354
355    // Write the test data to a file
356    private void writedata(String filename, String data)
357    {
358        File cardFile = new File(filename);
359        // If a cardfile exists, leave it
360        if (!cardFile.exists())
361        {
362            PrintWriter writer = null;
363            try
364            {
365                writer = new PrintWriter(new FileWriter(filename));
366                writer.println(data);
367                writer.close();
368            } catch (Exception ex)
369            {
370                ex.printStackTrace();
371            }
372        }
373    }
374    private static final String cardfileData =
375            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
376            + "<!--Please do not modify titles. Note that these titles are not"
377            + "sent into the actual screen. If titles are to be modified,"
378            + "they need to be changed in CardfileHandler.java  -->"
379            + ""
380            + ""
381            + ""
382            + "<CARDFILE> "
383            + " <TAB title = \"Coastal Division Units\">"
384            + "         <CARDFILE_OBJ name = \"Name\" >"
385            + "                 <ADDRESS>Address</ADDRESS>"
386            + "                 <CITY>City</CITY>"
387            + "                 <STATE>State</STATE>"
388            + "                 <ZIP>Zip</ZIP>"
389            + "                 <PHONE1>Phone1</PHONE1>"
390            + "                 <PHONE2>Phone2</PHONE2>"
391            + "                 <FAX>Fax</FAX>"
392            + "         </CARDFILE_OBJ>"
393            + "         "
394            + "         <CARDFILE_OBJ  name = \"Name2\" >"
395            + "                 <ADDRESS>Address2</ADDRESS>"
396            + "                 <CITY>City2</CITY>"
397            + "                 <STATE>State2</STATE>"
398            + "                 <ZIP>Zip2</ZIP>"
399            + "                 <PHONE1>Phone12</PHONE1>"
400            + "                 <PHONE2>Phone22</PHONE2>"
401            + "                 <FAX>Fax2</FAX>"
402            + "         </CARDFILE_OBJ>"
403            + "         "
404            + " </TAB>"
405            + " "
406            + " <TAB title = \"Police/Sheriff/Coroner\">"
407            + " "
408            + "         <CARDFILE_OBJ  name = \"Name\" >"
409            + "                 <ADDRESS>Address</ADDRESS>"
410            + "                 <CITY>City</CITY>"
411            + "                 <STATE>State</STATE>"
412            + "                 <ZIP>Zip</ZIP>"
413            + "                 <PHONE1>Phone1</PHONE1>"
414            + "                 <PHONE2>Phone2</PHONE2>"
415            + "                 <FAX>Fax</FAX>"
416            + "         </CARDFILE_OBJ>"
417            + "         "
418            + " </TAB>"
419            + " "
420            + " <TAB title = \"Courts\">"
421            + "         "
422            + "         "
423            + "         "
424            + " </TAB>"
425            + " "
426            + " <TAB title = \"Public Transportation\">"
427            + "         "
428            + "         "
429            + "         "
430            + " </TAB>"
431            + " "
432            + " <TAB title = \"GG Other\">"
433            + "         "
434            + "         "
435            + "         "
436            + " </TAB>"
437            + " "
438            + " <TAB title = \"MY Misc\">"
439            + "         "
440            + "         "
441            + "         "
442            + " </TAB>"
443            + " "
444            + " <TAB title = \"SL Misc\">"
445            + "         "
446            + "         "
447            + "         "
448            + " </TAB>"
449            + " "
450            + " <TAB title = \"VT Misc\">"
451            + "         "
452            + "         "
453            + "         "
454            + " </TAB>"
455            + " "
456            + " <TAB title = \"CHP Offices\">"
457            + "         "
458            + "         "
459            + "         "
460            + " </TAB>"
461            + " "
462            + " <TAB title = \"State Agencies/Facilities\">"
463            + "         "
464            + "         "
465            + "         "
466            + " </TAB>"
467            + " "
468            + " <TAB title = \"Government Officials\">"
469            + "         "
470            + "         "
471            + "         "
472            + " </TAB>"
473            + " "
474            + " <TAB title = \"Federal Agencies\">"
475            + "         "
476            + "         "
477            + "         "
478            + " </TAB>"
479            + " "
480            + " <TAB title = \"Fire/EMS\">"
481            + "         "
482            + "         "
483            + "         "
484            + " </TAB>"
485            + " "
486            + " <TAB title = \"Jails\">"
487            + "         "
488            + "         "
489            + "         "
490            + " </TAB>"
491            + " "
492            + " <TAB title = \"Hospitals/Med Centers\">"
493            + "         "
494            + "         "
495            + "         "
496            + " </TAB>"
497            + " "
498            + " <TAB title = \"Tow Companies\">"
499            + "         "
500            + "         "
501            + "         "
502            + " </TAB>"
503            + " "
504            + " <TAB title = \"CalTrans\">"
505            + "         "
506            + "         "
507            + "         "
508            + " </TAB>"
509            + " "
510            + " <TAB title = \"County Roads\">"
511            + "         "
512            + "         "
513            + "         "
514            + " </TAB>"
515            + " "
516            + " <TAB title = \"Utilities\">"
517            + "         "
518            + "         "
519            + "         "
520            + " </TAB>"
521            + " "
522            + " <TAB title = \"Animal Control\">"
523            + "         "
524            + "         "
525            + "         "
526            + " </TAB>"
527            + " "
528            + " <TAB title = \"Airports\">"
529            + "         "
530            + "         "
531            + "         "
532            + " </TAB>"
533            + " "
534            + " <TAB title = \"Credit Cards\">"
535            + "         "
536            + "         "
537            + "         "
538            + " </TAB>"
539            + " "
540            + " <TAB title = \"GG Crisis Shelters\">"
541            + "         "
542            + "         "
543            + "         "
544            + " </TAB>"
545            + " "
546            + " <TAB title = \"Ranges\">"
547            + "         "
548            + "         "
549            + "         "
550            + " </TAB>"
551            + " "
552            + " <TAB title = \"Hotlines\">"
553            + "         "
554            + "         "
555            + "         "
556            + " </TAB>"
557            + " "
558            + " <TAB title = \"Hwy Patrols OOS\">"
559            + "         "
560            + "         "
561            + "         "
562            + " </TAB>"
563            + " "
564            + " <TAB title = \"Parks/Recreation\">"
565            + "         "
566            + "         "
567            + "         "
568            + " </TAB>"
569            + " "
570            + " <TAB title = \"Shelters\">"
571            + "         "
572            + "         "
573            + "         "
574            + " </TAB>"
575            + " "
576            + " <TAB title = \"SL County Services\">"
577            + "         "
578            + "         "
579            + "         "
580            + " </TAB>"
581            + " "
582            + " <TAB title = \"SL Resources\">"
583            + "         "
584            + "         "
585            + "         "
586            + " </TAB>"
587            + " "
588            + " <TAB title = \"Truck/Tire Repair\">"
589            + "         "
590            + "         "
591            + "         "
592            + " </TAB>"
593            + " "
594            + " <TAB title = \"MCC Employees\">"
595            + "         "
596            + "         "
597            + "         "
598            + " </TAB>"
599            + " "
600            + " <TAB title = \"Gate Access Codes\">"
601            + "         "
602            + "         "
603            + "         "
604            + " </TAB>"
605            + " "
606            + " <TAB title = \"VT Call Signs\">"
607            + "         "
608            + "         "
609            + "         "
610            + " </TAB>"
611            + " "
612            + " <TAB title = \"SLCC Employees\">"
613            + "         "
614            + "         "
615            + "         "
616            + " </TAB>"
617            + ""
618            + "</CARDFILE>";
619    private static final String oneincidentXML =
620            "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>"
621            + ""
622            + "<TMC_SCRIPT title=\"One Incident Simulation\">"
623            + ""
624            + " <SCRIPT_EVENT>"
625            + "         <TIME_INDEX>00:00:00</TIME_INDEX>"
626            + "         <INCIDENT LogNum=\"100\">Media Log</INCIDENT>           "
627            + "         "
628            + "         <CAD_DATA>"
629            + "                 <HEADER_INFO>"
630            + "                         <Type>Media</Type>"
631            + "                         <Beat>"
632            + "                         </Beat>"
633            + "                         <TruncLoc>"
634            + "                         </TruncLoc>"
635            + "                         <FullLoc>"
636            + "                         </FullLoc>"
637            + "                 </HEADER_INFO>                  "
638            + "                 "
639            + "                 <CAD_INCIDENT_EVENT>    "
640            + "                 </CAD_INCIDENT_EVENT>           "
641            + "                 "
642            + "         </CAD_DATA>                             "
643            + "         "
644            + " </SCRIPT_EVENT> "
645            + "</TMC_SCRIPT>";
646}
Note: See TracBrowser for help on using the repository browser.