-
Notifications
You must be signed in to change notification settings - Fork 72
/
Copy pathFullTests.cpp
1719 lines (1353 loc) · 67.2 KB
/
FullTests.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// FullTests.cpp
// Soar-xcode
//
// Created by Alex Turner on 6/26/15.
// Copyright © 2015 University of Michigan – Soar Group. All rights reserved.
//
#include "FullTests.hpp"
#include "FullTestsClientThread.hpp"
#include "FullTestsClientThreadFullyOptimized.hpp"
#include "FullTestsRemote.hpp"
#include "SoarHelper.hpp"
#include "sml_AgentSML.h"
#include "sml_ClientKernel.h"
#include "soar_instance.h"
#include <functional>
bool g_Cancel = false;
#ifdef _WIN32
BOOL WINAPI handle_ctrlc(DWORD dwCtrlType)
{
if (dwCtrlType == CTRL_C_EVENT)
{
g_Cancel = true;
return TRUE;
}
return FALSE;
}
#else // _WIN32
#include <spawn.h>
#endif // not _WIN32
const std::string FullTests_Parent::kAgentName("full-tests-agent");
void FullTests_Parent::setUp()
{
no_agent_assertTrue(MAJOR_VERSION_NUMBER == SML_MAJOR_VERSION_NUMBER);
no_agent_assertTrue(MINOR_VERSION_NUMBER == SML_MINOR_VERSION_NUMBER);
no_agent_assertTrue(MICRO_VERSION_NUMBER == SML_MICRO_VERSION_NUMBER);
no_agent_assertTrue(GREEK_VERSION_NUMBER == SML_GREEK_VERSION_NUMBER);
no_agent_assertTrue(strcmp(VERSION_STRING(), SML_VERSION_STRING()) == 0);
m_pKernel = 0;
agent = 0;
createSoar();
}
void FullTests_Parent::tearDown(bool caught)
{
destroySoar();
}
void FullTestsClientThreadFullyOptimized::setUp()
{
FullTests_Parent::runner = TestCategory::runner;
m_Options.reset();
m_Options.useClientThread = true;
m_Options.fullyOptimized = true;
FullTests_Parent::setUp();
}
void FullTestsClientThread::setUp()
{
FullTests_Parent::runner = TestCategory::runner;
m_Options.reset();
m_Options.useClientThread = true;
FullTests_Parent::setUp();
}
void FullTests::setUp()
{
FullTests_Parent::runner = TestCategory::runner;
m_Options.reset();
FullTests_Parent::setUp();
}
void FullTestsRemote::setUp()
{
FullTests_Parent::runner = TestCategory::runner;
m_Options.reset();
m_Options.remote = true;
FullTests_Parent::setUp();
}
void FullTests_Parent::createSoar()
{
no_agent_assertTrue(m_pKernel == NULL);
if (m_Options.remote)
{
int targetPid = spawnListener();
m_pKernel = sml::Kernel::CreateRemoteConnection(true, 0, targetPid);
}
else
{
if (m_Options.useClientThread)
{
bool optimized = m_Options.fullyOptimized;
m_pKernel = sml::Kernel::CreateKernelInCurrentThread(optimized, sml::Kernel::kUseAnyPort);
}
else
{
m_pKernel = sml::Kernel::CreateKernelInNewThread(sml::Kernel::kUseAnyPort);
}
if (SoarHelper::run_as_unit_test)
{
configure_for_unit_tests();
}
}
no_agent_assertTrue(m_pKernel != NULL);
no_agent_assertTrue_msg(m_pKernel->GetLastErrorDescription(), !m_pKernel->HadError());
if (m_Options.verbose)
{
std::cout << "Soar kernel version " << m_pKernel->GetSoarKernelVersion() << std::endl ;
}
if (m_Options.verbose)
{
std::cout << "SML version " << sml::sml_Names::kSMLVersionValue << std::endl ;
}
no_agent_assertTrue(std::string(m_pKernel->GetSoarKernelVersion()) == std::string(sml::sml_Names::kSoarVersionValue));
bool creationHandlerReceived(false);
int agentCreationCallback = m_pKernel->RegisterForAgentEvent(sml::smlEVENT_AFTER_AGENT_CREATED, Handlers::MyCreationHandler, &creationHandlerReceived) ;
// Report the number of agents (always 0 unless this is a remote connection to a CLI or some such)
no_agent_assertTrue(m_pKernel->GetNumberAgents() == 0);
// NOTE: We don't delete the agent pointer. It's owned by the kernel
agent = m_pKernel->CreateAgent(kAgentName.c_str()) ;
no_agent_assertTrue_msg(m_pKernel->GetLastErrorDescription(), !m_pKernel->HadError());
no_agent_assertTrue(agent != NULL);
no_agent_assertTrue(creationHandlerReceived);
if (SoarHelper::run_as_unit_test)
{
agent_struct* lAgent = Soar_Instance::Get_Soar_Instance().Get_Agent_Info(kAgentName.c_str())->GetSoarAgent();
configure_agent_for_unit_tests(lAgent);
}
no_agent_assertTrue(m_pKernel->UnregisterForAgentEvent(agentCreationCallback));
// a number of tests below depend on running full decision cycles.
agent->ExecuteCommandLine("soar stop-phase input") ;
no_agent_assertTrue_msg("soar stop-phase input", agent->GetLastCommandLineResult());
no_agent_assertTrue(m_pKernel->GetNumberAgents() == 1);
m_pKernel->SetAutoCommit(!m_Options.autoCommitDisabled) ;
}
void FullTests_Parent::destroySoar()
{
if (!m_pKernel)
return;
// Agent deletion
if (m_Options.verbose)
{
std::cout << "Destroy the agent now" << std::endl ;
}
// The Before_Agent_Destroyed callback is a tricky one so we'll register for it to test it.
// We need to get this callback just before the agentSML data is deleted (otherwise there'll be no way to send/receive the callback)
// and then continue on to delete the agent after we've responded to the callback.
// Interestingly, we don't explicitly unregister this callback because the agent has already been destroyed so
// that's another test, that this callback is cleaned up correctly (and automatically).
bool deletionHandlerReceived(false);
m_pKernel->RegisterForAgentEvent(sml::smlEVENT_BEFORE_AGENT_DESTROYED, Handlers::MyDeletionHandler, &deletionHandlerReceived) ;
// Explicitly destroy our agent as a test, before we delete the kernel itself.
// (Actually, if this is a remote connection we need to do this or the agent
// will remain alive).
no_agent_assertTrue(m_pKernel->DestroyAgent(agent));
no_agent_assertTrue(deletionHandlerReceived);
deletionHandlerReceived = false;
if (m_Options.verbose)
{
std::cout << "Calling shutdown on the kernel now" << std::endl ;
}
if (m_Options.remote)
{
soar_thread::Event shutdownEvent;
m_pKernel->RegisterForSystemEvent(sml::smlEVENT_BEFORE_SHUTDOWN, Handlers::MyEventShutdownHandler, &shutdownEvent) ;
// BUGBUG
// ClientSML thread dies inelegantly here spewing forth error messages
// about sockets/pipes not being shut down correctly.
std::string shutdownResponse = m_pKernel->SendClientMessage(0, "test-listener", "shutdown") ;
no_agent_assertTrue(shutdownResponse == "ok");
no_agent_assertTrue_msg("Listener side kernel shutdown failed to fire smlEVENT_BEFORE_SHUTDOWN", shutdownEvent.WaitForEvent(5, 0));
// Note, in the remote case, this does not fire smlEVENT_BEFORE_SHUTDOWN
// the listener side shutdown does trigger the event when it is deleted, see simplelistener.cpp
m_pKernel->Shutdown() ;
}
else
{
bool shutdownHandlerReceived(false);
m_pKernel->RegisterForSystemEvent(sml::smlEVENT_BEFORE_SHUTDOWN, Handlers::MyBoolShutdownHandler, &shutdownHandlerReceived) ;
m_pKernel->Shutdown() ;
no_agent_assertTrue(shutdownHandlerReceived);
}
if (m_Options.verbose)
{
std::cout << "Shutdown completed now" << std::endl ;
}
// Delete the kernel. If this is an embedded connection this destroys the kernel.
// If it's a remote connection we just disconnect.
delete m_pKernel ;
m_pKernel = NULL;
if (m_Options.remote)
{
cleanUpListener();
if (m_Options.verbose)
{
std::cout << "Cleaned up listener." << std::endl;
}
}
}
int FullTests_Parent::spawnListener()
{
// Spawning a new process is radically different on windows vs linux.
// Instead of writing an abstraction layer, I'm just going to put platform-
// specific code here.
int targetPid = -1;
#ifdef _WIN32
ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
ZeroMemory(&pi, sizeof(pi));
char executable[1024];
GetModuleFileName(NULL, executable, 1024);
// Start the child process.
BOOL success = CreateProcess(executable,
"Prototype-UnitTesting.exe --listener", // Command line
NULL, // Process handle not inheritable
NULL, // Thread handle not inheritable
FALSE, // Set handle inheritance to FALSE
0, // No creation flags
NULL, // Use parent's environment block
NULL, // Use parent's starting directory
&si, // Pointer to STARTUPINFO structure
&pi); // Pointer to PROCESS_INFORMATION structure
std::stringstream errorMessage;
errorMessage << "CreateProcess error code: " << GetLastError();
no_agent_assertTrue_msg(errorMessage.str().c_str(), success);
targetPid = pi.dwProcessId;
#else // _WIN32
std::string executable = SoarHelper::GetResource("Prototype-UnitTesting");
char arg1[22] = {"Prototype-UnitTesting"};
char arg2[11] = {"--listener"};
char* argv[] = {arg1, arg2, NULL};
int error = posix_spawn(&targetPid, executable.c_str(), NULL, NULL, argv, NULL);
no_agent_assertTrue_msg("posix_spawn error", error == 0);
#endif // _WIN32
sml::Sleep(1, 0);
return targetPid;
}
void FullTests_Parent::cleanUpListener()
{
#ifdef _WIN32
// Wait until child process exits.
WaitForSingleObject(pi.hProcess, INFINITE);
// Close process and thread handles.
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
#else // _WIN32
int status(0);
wait(&status);
if (WIFEXITED(status))
{
no_agent_assertTrue_msg("listener terminated with nonzero status", WEXITSTATUS(status) == 0);
}
else
{
no_agent_assertTrue_msg("listener killed by signal", WIFSIGNALED(status));
// not sure why signal 0 comes up but seems to fix things on Mac OS
if (!WIFSTOPPED(status) && (WSTOPSIG(status) != 0))
{
no_agent_assertTrue_msg("listener stopped by signal", WIFSTOPPED(status));
}
else if (WIFSTOPPED(status))
{
#ifndef WIFCONTINUED
#define __W_CONTINUED 0xffff
#define __WIFCONTINUED(status) ((status) == __W_CONTINUED)
#define __WAIT_INT(status) (*(__const int *) &(status))
#define WIFCONTINUED(status) __WIFCONTINUED(__WAIT_INT(status))
#endif
no_agent_assertTrue_msg("listener continued", WIFCONTINUED(status));
no_agent_assertTrue_msg("listener died: unknown", false);
}
}
#endif // _WIN32
}
void FullTests_Parent::loadProductions(std::string productions)
{
agent->LoadProductions(productions.c_str(), true) ;
no_agent_assertTrue_msg("loadProductions", agent->GetLastCommandLineResult());
SoarHelper::check_learning_override(agent);
}
void FullTests_Parent::testInit()
{
agent->InitSoar();
no_agent_assertTrue_msg("init-soar", agent->GetLastCommandLineResult());
}
void FullTests_Parent::testProductions()
{
// Load and test productions
loadProductions(SoarHelper::GetResource("testsml.soar"));
no_agent_assertTrue(agent->IsProductionLoaded("apply*move"));
no_agent_assertTrue(!agent->IsProductionLoaded("made*up*name"));
int excisedCount(0);
int prodCall = agent->RegisterForProductionEvent(sml::smlEVENT_BEFORE_PRODUCTION_REMOVED, Handlers::MyProductionHandler, &excisedCount) ;
agent->ExecuteCommandLine("excise --all") ;
no_agent_assertTrue_msg("excise --all", agent->GetLastCommandLineResult());
no_agent_assertTrue(excisedCount > 0);
excisedCount = 0;
loadProductions(SoarHelper::GetResource("testsml.soar"));
no_agent_assertTrue(excisedCount == 0);
no_agent_assertTrue(agent->UnregisterForProductionEvent(prodCall));
SoarHelper::init_check_to_find_refcount_leaks(agent);
}
void FullTests_Parent::testUngroundedLHS()
{
// We're testing warnings here, so turn them on
agent->ExecuteCommandLine("output warnings on");
// This is the standard way to match the state
std::string result = agent->ExecuteCommandLine("sp { ok*standard (state <s> ^superstate nil) -->}");
no_agent_assertTrue(agent->GetLastCommandLineResult());
// Explicit ID test is not required on state
result = agent->ExecuteCommandLine("sp { ok*no*explicit*id*test (state ^superstate nil) -->}");
no_agent_assertTrue(agent->GetLastCommandLineResult());
// Wildcard matches are also fine
result = agent->ExecuteCommandLine("sp { ok*wildcard (state ^<any1> <any2>) -->}");
no_agent_assertTrue(agent->GetLastCommandLineResult());
// Matches on just <s> will add the attr-val tests automatically
result = agent->ExecuteCommandLine("sp { ok*lone*s (state <s> ^superstate nil) (<s>) -->}");
no_agent_assertTrue(agent->GetLastCommandLineResult());
// TODO: this warns but should also fail, as there's no state test
result = agent->ExecuteCommandLine("sp {warns*no*state*test (<s> ^results <any>)-->}");
no_agent_assertTrue(agent->GetLastCommandLineResult());
const char* expected_message = "Warning: On the LHS of production warns*no*state*test, identifier <s> is not connected to any goal or impasse.";
no_agent_assertTrue_msg("Expected1 warning message not found in '" + result + "'", result.find(expected_message) != std::string::npos);
// at least one attr/val test is required with state test
result = agent->ExecuteCommandLine("sp { fails*no*attr*val*test (state <s>) -->}");
no_agent_assertFalse(agent->GetLastCommandLineResult());
expected_message = "Error: Expected attribute-value test after state/impasse test. Did you forget to add \"^type state\" or \"^superstate nil\"?";
no_agent_assertTrue_msg("Expected2 error message not found in '" + result + "'", result.find(expected_message) != std::string::npos);
// We require the attr/val test to be in the same condition as the state test
result = agent->ExecuteCommandLine("sp { fails*missing*attr*val*test (state <s>) (<s> ^superstate nil) -->}");
no_agent_assertFalse(agent->GetLastCommandLineResult());
expected_message = "Error: Expected attribute-value test after state/impasse test. Did you forget to add \"^type state\" or \"^superstate nil\"?";
no_agent_assertTrue_msg("Expected3 error message not found in '" + result + "'", result.find(expected_message) != std::string::npos);
// negative conditions do not serve to ground the state
result = agent->ExecuteCommandLine("sp { fails*negative*doesnt*ground (state -^result <any>) -->}");
no_agent_assertFalse(agent->GetLastCommandLineResult());
expected_message = "Error: production fails*negative*doesnt*ground has no positive conditions that reference a goal state.\nDid you forget to add \"^type state\" or \"^superstate nil\"?";
no_agent_assertTrue_msg("Expected4 error message not found in '" + result + "'", result.find(expected_message) != std::string::npos);
}
void FullTests_Parent::testRHSHandler()
{
loadProductions(SoarHelper::GetResource("testsml.soar"));
bool rhsFunctionHandlerReceived(false);
// Record a RHS function
int callback_rhs1 = m_pKernel->AddRhsFunction("test-rhs", Handlers::MyRhsFunctionHandler, &rhsFunctionHandlerReceived) ;
int callback_rhs_dup = m_pKernel->AddRhsFunction("test-rhs", Handlers::MyRhsFunctionHandler, &rhsFunctionHandlerReceived) ;
//agent->RegisterForPrintEvent( sml::smlEVENT_PRINT, Handlers::DebugPrintEventHandler, 0) ;
no_agent_assertTrue_msg("Duplicate RHS function registration should be detected and be ignored", callback_rhs_dup == callback_rhs1);
bool cppRhsHandlerReceived(false);
int callback_rhs_cpp = m_pKernel->AddRhsFunction("test-rhs-cpp", Handlers::GetRhsFunctionHandlerCpp(&cppRhsHandlerReceived)) ;
// need this to fire production that calls test-rhs
sml::Identifier* pSquare = agent->GetInputLink()->CreateIdWME("square") ;
no_agent_assertTrue(pSquare);
sml::StringElement* pEmpty = pSquare->CreateStringWME("content", "EMPTY") ;
no_agent_assertTrue(pEmpty);
sml::IntElement* pRow = pSquare->CreateIntWME("row", 1) ;
no_agent_assertTrue(pRow);
sml::IntElement* pCol = pSquare->CreateIntWME("col", 2) ;
no_agent_assertTrue(pCol);
no_agent_assertTrue(agent->Commit());
m_pKernel->RunAllAgents(1) ;
no_agent_assertTrue_msg("RunAllAgents", agent->GetLastCommandLineResult());
//std::cout << agent->ExecuteCommandLine("p i2 --depth 4") << std::endl;
no_agent_assertTrue(rhsFunctionHandlerReceived);
no_agent_assertTrue(cppRhsHandlerReceived);
no_agent_assertTrue(m_pKernel->RemoveRhsFunction(callback_rhs1));
no_agent_assertTrue(m_pKernel->RemoveRhsFunction(callback_rhs_cpp));
// Re-add it without the bool that is getting popped off the stack
no_agent_assertTrue(m_pKernel->AddRhsFunction("test-rhs", Handlers::MyRhsFunctionHandler, 0));
no_agent_assertTrue(pSquare->DestroyWME());
no_agent_assertTrue(agent->Commit());
SoarHelper::init_check_to_find_refcount_leaks(agent);
}
void FullTests_Parent::testClientMessageHandler()
{
// Record a client message handler
bool clientHandlerReceived(false);
int clientCallback = m_pKernel->RegisterForClientMessageEvent("test-client", Handlers::MyClientMessageHandler, &clientHandlerReceived) ;
bool clientHandlerReceivedCpp(false);
int clientCallbackCpp = m_pKernel->RegisterForClientMessageEvent("test-client-cpp", Handlers::GetClientMessageHandlerCpp(&clientHandlerReceivedCpp)) ;
// This is a bit dopey--but we'll send a message to ourselves for this test
std::string message("foo-bar-baz-qux");
std::string response = m_pKernel->SendClientMessage(agent, "test-client", message.c_str());
no_agent_assertTrue(clientHandlerReceived);
std::string expected = "handler-message" + message;
no_agent_assertTrue(response == expected);
response = m_pKernel->SendClientMessage(agent, "test-client-cpp", message.c_str());
no_agent_assertTrue(clientHandlerReceivedCpp);
expected = "handler-message-cpp" + message;
no_agent_assertTrue(response == expected);
no_agent_assertTrue(m_pKernel->UnregisterForClientMessageEvent(clientCallback));
no_agent_assertTrue(m_pKernel->UnregisterForClientMessageEvent(clientCallbackCpp));
}
void FullTests_Parent::testFilterHandler()
{
// Record a filter
bool filterHandlerReceived(false);
int clientFilter = m_pKernel->RegisterForClientMessageEvent(sml::sml_Names::kFilterName, Handlers::MyFilterHandler, &filterHandlerReceived) ;
// Our filter adds "--depth 2" to all commands
// so this should give us the result of "print s1 --depth 2"
std::string output = agent->ExecuteCommandLine("print <s>") ;
no_agent_assertTrue_msg("print <s>", agent->GetLastCommandLineResult());
no_agent_assertTrue(filterHandlerReceived);
filterHandlerReceived = false;
// depth 2 should reveal I2
no_agent_assertTrue(output.find("input-link") != std::string::npos);
// This is important -- if we don't unregister all subsequent commands will
// come to our filter and promptly fail!
no_agent_assertTrue(m_pKernel->UnregisterForClientMessageEvent(clientFilter));
}
void FullTests_Parent::testWMEs()
{
sml::Identifier* pInputLink = agent->GetInputLink() ;
no_agent_assertTrue(pInputLink);
// Some simple tests
sml::StringElement* pWME = pInputLink->CreateStringWME("my-att", "my-value") ;
no_agent_assertTrue(pWME);
// This is to test a bug where an identifier isn't fully removed from working memory (you can still print it) after it is destroyed.
sml::Identifier* pIDRemoveTest = pInputLink->CreateIdWME("foo") ;
no_agent_assertTrue(pIDRemoveTest);
no_agent_assertTrue(pIDRemoveTest->CreateFloatWME("bar", 1.23));
no_agent_assertTrue(pIDRemoveTest->GetValueAsString());
sml::Identifier* pID = pInputLink->CreateIdWME("plane") ;
no_agent_assertTrue(pID);
// Trigger for inputWme update change problem
sml::StringElement* pWMEtest = pID->CreateStringWME("typeTest", "Boeing747") ;
no_agent_assertTrue(pWMEtest);
no_agent_assertTrue(agent->Commit());
agent->RunSelf(1) ;
no_agent_assertTrue_msg("RunSelf", agent->GetLastCommandLineResult());
no_agent_assertTrue(pIDRemoveTest->DestroyWME());
no_agent_assertTrue(agent->Commit());
//agent->RunSelf(1) ;
no_agent_assertTrue(agent->ExecuteCommandLine("print i2 --depth 3"));
no_agent_assertTrue_msg("print i2 --depth 3", agent->GetLastCommandLineResult());
no_agent_assertTrue(agent->ExecuteCommandLine("print F1")); // BUGBUG: This wme remains in memory even after we add the "RunSelf" at which point it should be gone.
no_agent_assertTrue_msg("print F1", agent->GetLastCommandLineResult());
agent->InitSoar();
no_agent_assertTrue_msg("init-soar", agent->GetLastCommandLineResult());
no_agent_assertTrue(pID->CreateStringWME("type", "Boeing747"));
sml::IntElement* pWME2 = pID->CreateIntWME("speed", 200) ;
no_agent_assertTrue(pWME2);
sml::FloatElement* pWME3 = pID->CreateFloatWME("direction", 50.5) ;
no_agent_assertTrue(pWME3);
no_agent_assertTrue(agent->Commit());
agent->InitSoar();
no_agent_assertTrue_msg("init-soar", agent->GetLastCommandLineResult());
// Test the blink option
agent->SetBlinkIfNoChange(false) ;
int64_t timeTag1 = pWME3->GetTimeTag() ;
agent->Update(pWME3, 50.5) ; // Should not change the wme, so timetag should be the same
int64_t timeTag2 = pWME3->GetTimeTag() ;
agent->SetBlinkIfNoChange(true) ; // Back to the default
agent->Update(pWME3, 50.5) ; // Should change the wme, so timetag should be different
int64_t timeTag3 = pWME3->GetTimeTag() ;
no_agent_assertTrue_msg("Error in handling of SetBlinkIfNoChange flag", timeTag1 == timeTag2);
no_agent_assertTrue_msg("Error in handling of SetBlinkIfNoChange flag", timeTag2 != timeTag3);
// Remove a wme
no_agent_assertTrue(pWME3->DestroyWME());
// Change the speed to 300
agent->Update(pWME2, 300) ;
// Create a new WME that shares the same id as plane
// BUGBUG: This is triggering an no_agent_assert and memory leak now after the changes
// to InputWME not calling Update() immediately. For now I've removed the test until
// we have time to figure out what's going wrong.
//Identifier* pID2 = agent->CreateSharedIdWME(pInputLink, "all-planes", pID) ;
//unused(pID2);
no_agent_assertTrue(agent->Commit());
/*
printWMEs(agent->GetInputLink()) ;
std::string printInput1 = agent->ExecuteCommandLine("print --depth 2 I2") ;
std::cout << printInput1 << std::endl ;
std::cout << std::endl << "Now work with the input link" << std::endl ;
*/
// Delete one of the shared WMEs to make sure that's ok
//agent->DestroyWME(pID) ;
//agent->Commit() ;
// Throw in a pattern as a test
std::string pattern = agent->ExecuteCommandLine("print -i (s1 ^* *)") ;
no_agent_assertTrue_msg("print -i (s1 ^* *)", agent->GetLastCommandLineResult());
SoarHelper::init_check_to_find_refcount_leaks(agent);
}
void FullTests_Parent::testXML()
{
// Test calling CommandLineXML.
sml::ClientAnalyzedXML xml2 ;
no_agent_assertTrue(m_pKernel->ExecuteCommandLineXML("print -i --depth 3 s1", agent->GetAgentName(), &xml2));
char* xmlString = xml2.GenerateXMLString(true);
no_agent_assertTrue(xmlString);
soarxml::ElementXML const* pResult = xml2.GetResultTag() ;
no_agent_assertTrue(pResult);
// The XML format of "print" is a <trace> tag containing a series of
// a) <wme> tags (if this is an --internal print) or
// b) <id> tags that contain <wme> tags if this is not an --internal print.
soarxml::ElementXML traceChild ;
no_agent_assertTrue(pResult->GetChild(&traceChild, 0));
int nChildren = traceChild.GetNumberChildren() ;
soarxml::ElementXML wmeChild ;
for (int i = 0 ; i < nChildren ; i++)
{
traceChild.GetChild(&wmeChild, i) ;
char* wmeString = wmeChild.GenerateXMLString(true) ;
no_agent_assertTrue(wmeString);
if (m_Options.verbose)
{
std::cout << wmeString << std::endl ;
}
wmeChild.DeleteString(wmeString) ;
}
xml2.DeleteString(xmlString) ;
}
void FullTests_Parent::testAgent()
{
//m_pKernel->SetTraceCommunications( true );
agent->SetOutputLinkChangeTracking(true);
loadProductions(SoarHelper::GetResource("testsml.soar"));
// Test that we get a callback after the decision cycle runs
// We'll pass in an "int" and use it to count decisions (just as an example of passing user data around)
int count(0);
int callback1 = agent->RegisterForRunEvent(sml::smlEVENT_AFTER_DECISION_CYCLE, Handlers::MyRunEventHandler, &count);
int callback_dup = agent->RegisterForRunEvent(sml::smlEVENT_AFTER_DECISION_CYCLE, Handlers::MyRunEventHandler, &count);
no_agent_assertTrue_msg("Duplicate handler registration should be detected and be ignored", callback1 == callback_dup);
// This callback unregisters itself in the callback -- as a test to see if we can do that safely.
int selfRemovingCallback(-1);
selfRemovingCallback = agent->RegisterForRunEvent(sml::smlEVENT_AFTER_DECISION_CYCLE, Handlers::MyRunSelfRemovingHandler, &selfRemovingCallback) ;
// Register for a String event
// bool stringEventHandlerReceived(false);
// int stringCall = m_pKernel->RegisterForStringEvent(sml::smlEVENT_LOAD_LIBRARY, Handlers::MyStringEventHandler, &stringEventHandlerReceived) ;
// no_agent_assertTrue(m_pKernel->ExecuteCommandLine("load-library TestExternalLibraryLib", NULL));
// no_agent_assertTrue_msg("echo hello world", agent->GetLastCommandLineResult());
// no_agent_assertTrue(stringEventHandlerReceived);
// stringEventHandlerReceived = false;
// no_agent_assertTrue(m_pKernel->UnregisterForStringEvent(stringCall));
// Register another handler for the same event, to make sure we can do that.
// Register this one ahead of the previous handler (so it will fire before MyRunEventHandler)
bool addToBack = true ;
int testData(25) ;
int callback2 = agent->RegisterForRunEvent(sml::smlEVENT_AFTER_DECISION_CYCLE, Handlers::MyDuplicateRunEventHandler, &testData, !addToBack) ;
// Run returns the result (succeeded, failed etc.)
// To catch the trace output we have to register a print event listener
std::stringstream trace ; // We'll pass this into the handler and build up the output in it
std::string structured ; // Structured trace goes here
int callbackp = agent->RegisterForPrintEvent(sml::smlEVENT_PRINT, Handlers::MyPrintEventHandler, &trace) ;
sml::ClientXML* clientXMLStorage = 0;
int callbackx = agent->RegisterForXMLEvent(sml::smlEVENT_XML_TRACE_OUTPUT, Handlers::MyXMLEventHandler, &clientXMLStorage) ;
int beforeCount(0);
int afterCount(0);
int callback_before = agent->RegisterForRunEvent(sml::smlEVENT_BEFORE_RUN_STARTS, Handlers::MyRunEventHandler, &beforeCount) ;
int callback_after = agent->RegisterForRunEvent(sml::smlEVENT_AFTER_RUN_ENDS, Handlers::MyRunEventHandler, &afterCount) ;
//Some temp code to generate more complex watch traces. Not usually part of the test
/*
Identifier* pSquare1 = agent->CreateIdWME(pInputLink, "square") ;
StringElement* pEmpty1 = pSquare1->CreateStringWME("content", "RANDOM") ;
IntElement* pRow1 = agent->CreateIntWME(pSquare1, "row", 1) ;
IntElement* pCol1 = agent->CreateIntWME(pSquare1, "col", 2) ;
agent->Update(pEmpty1, "EMPTY") ;
ok = agent->Commit() ;
agent->ExecuteCommandLine("watch 3") ;
*/
// Test that we get a callback after the all output phases complete
// We'll pass in an "int" and use it to count output phases
int outputPhases(0);
int callback_u = m_pKernel->RegisterForUpdateEvent(sml::smlEVENT_AFTER_ALL_OUTPUT_PHASES, Handlers::MyUpdateEventHandler, &outputPhases) ;
int phaseCount(0);
int callbackPhase = agent->RegisterForRunEvent(sml::smlEVENT_BEFORE_PHASE_EXECUTED, Handlers::MyRunEventHandler, &phaseCount) ;
// Nothing should match here
agent->RunSelf(4) ;
no_agent_assertTrue_msg("RunSelf", agent->GetLastCommandLineResult());
// Should be one output phase per decision
no_agent_assertTrue(outputPhases == 4);
no_agent_assertTrue(agent->WasAgentOnRunList());
no_agent_assertTrue(agent->GetResultOfLastRun() == sml::sml_RUN_COMPLETED);
// Should be 5 phases per decision
/* Not true now we support stopping before/after phases when running by decision.
if (phaseCount != 20)
{
std::cout << "Error receiving phase events" << std::endl ;
return false ;
}
*/
no_agent_assertTrue(beforeCount == 1);
no_agent_assertTrue(afterCount == 1);
no_agent_assertTrue(agent->UnregisterForRunEvent(callbackPhase));
// By this point the static variable ClientXMLStorage should have been filled in
// and it should be valid, even though the event handler for MyXMLEventHandler has completed.
no_agent_assertTrue_msg("Error receiving XML trace events", clientXMLStorage != NULL);
// If we crash on this access there's a problem with the ref-counting of
// the XML message we're passed in MyXMLEventHandler.
no_agent_assertTrue(clientXMLStorage->ConvertToTraceXML()->IsTagTrace());
delete clientXMLStorage ;
clientXMLStorage = NULL ;
no_agent_assertTrue(agent->UnregisterForXMLEvent(callbackx));
no_agent_assertTrue(agent->UnregisterForPrintEvent(callbackp));
no_agent_assertTrue(agent->UnregisterForRunEvent(callback_before));
no_agent_assertTrue(agent->UnregisterForRunEvent(callback_after));
no_agent_assertTrue(m_pKernel->UnregisterForUpdateEvent(callback_u));
// Print out the standard trace and the same thing as a structured XML trace
if (m_Options.verbose)
{
std::cout << trace.str() << std::endl ;
}
trace.clear();
if (m_Options.verbose)
{
std::cout << structured << std::endl ;
}
/*
printWMEs(agent->GetInputLink()) ;
std::string printInput = agent->ExecuteCommandLine("print --depth 2 I2") ;
std::cout << printInput << std::endl ;
*/
// Then add some tic tac toe stuff which should trigger output
sml::Identifier* pSquare = agent->GetInputLink()->CreateIdWME("square") ;
no_agent_assertTrue(pSquare);
sml::StringElement* pEmpty = pSquare->CreateStringWME("content", "RANDOM") ;
no_agent_assertTrue(pEmpty);
sml::IntElement* pRow = pSquare->CreateIntWME("row", 1) ;
no_agent_assertTrue(pRow);
sml::IntElement* pCol = pSquare->CreateIntWME("col", 2) ;
no_agent_assertTrue(pCol);
no_agent_assertTrue(agent->Commit());
// Update the square's value to be empty. This ensures that the update
// call is doing something. Otherwise, when we run we won't get a match.
agent->Update(pEmpty, "EMPTY") ;
no_agent_assertTrue(agent->Commit());
int myCount(0);
int callback_run_count = agent->RegisterForRunEvent(sml::smlEVENT_AFTER_DECISION_CYCLE, Handlers::MyRunEventHandler, &myCount) ;
int outputsGenerated(0) ;
int callback_g = m_pKernel->RegisterForUpdateEvent(sml::smlEVENT_AFTER_ALL_GENERATED_OUTPUT, Handlers::MyUpdateEventHandler, &outputsGenerated) ;
int outputNotifications(0) ;
int callback_notify = agent->RegisterForOutputNotification(Handlers::MyOutputNotificationHandler, &outputNotifications) ;
// Can't test this at the same time as testing the getCommand() methods as registering for this clears the output link information
//int outputHandler = agent->AddOutputHandler("move", MyOutputEventHandler, NULL) ;
if (m_Options.verbose)
{
std::cout << "About to do first run-til-output" << std::endl ;
}
int callbackp1 = agent->RegisterForPrintEvent(sml::smlEVENT_PRINT, Handlers::MyPrintEventHandler, &trace) ;
// Now we should match (if we really loaded the tictactoe example rules) and so generate some real output
// We'll use RunAll just to test it out. Could use RunSelf and get same result (presumably)
m_pKernel->RunAllTilOutput() ; // Should just cause Soar to run a decision or two (this is a test that run til output works stops at output)
no_agent_assertTrue_msg("RunAllTilOutput", agent->GetLastCommandLineResult());
// We should stop quickly (after a decision or two)
no_agent_assertTrue_msg("Error in RunTilOutput -- it didn't stop on the output", myCount <= 10);
no_agent_assertTrue_msg("Error in callback handler for MyRunEventHandler -- failed to update count", myCount > 0);
if (m_Options.verbose)
{
std::cout << "Agent ran for " << myCount << " decisions before we got output" << std::endl ;
}
if (m_Options.verbose)
{
std::cout << trace.str() << std::endl ;
}
trace.clear();
no_agent_assertTrue_msg("Error in AFTER_ALL_GENERATED event.", outputsGenerated == 1);
no_agent_assertTrue_msg("Error in OUTPUT_NOTIFICATION event.", outputNotifications == 1);
// Reset the agent and repeat the process to check whether init-soar works.
agent->InitSoar();
no_agent_assertTrue_msg("init-soar", agent->GetLastCommandLineResult());
agent->RunSelfTilOutput() ;
no_agent_assertTrue_msg("RunSelfTilOutput", agent->GetLastCommandLineResult());
no_agent_assertTrue(agent->UnregisterForOutputNotification(callback_notify));
no_agent_assertTrue(m_pKernel->UnregisterForUpdateEvent(callback_g));
no_agent_assertTrue(agent->UnregisterForPrintEvent(callbackp1));
//cout << "Time to dump output link" << std::endl ;
no_agent_assertTrue(agent->GetOutputLink());
//printWMEs(agent->GetOutputLink()) ;
// Now update the output link with "status complete"
sml::Identifier* pMove = static_cast< sml::Identifier* >(agent->GetOutputLink()->FindByAttribute("move", 0));
no_agent_assertTrue(pMove);
// Try to find an attribute that's missing to make sure we get null back
sml::Identifier* pMissing = static_cast< sml::Identifier* >(agent->GetOutputLink()->FindByAttribute("not-there", 0));
no_agent_assertTrue(!pMissing);
sml::Identifier* pMissingInput = static_cast< sml::Identifier* >(agent->GetInputLink()->FindByAttribute("not-there", 0));
no_agent_assertTrue(!pMissingInput);
// We add an "alternative" to check that we handle shared WMEs correctly.
// Look it up here.
sml::Identifier* pAlt = static_cast< sml::Identifier* >(agent->GetOutputLink()->FindByAttribute("alternative", 0));
no_agent_assertTrue(pAlt);
// Should also be able to get the command through the "GetCommands" route which tests
// whether we've flagged the right wmes as "just added" or not.
int numberCommands = agent->GetNumberCommands() ;
no_agent_assertTrue(numberCommands == 3);
// Get the first two commands (move and alternative and A)
sml::Identifier* pCommand1 = agent->GetCommand(0) ;
sml::Identifier* pCommand2 = agent->GetCommand(1) ;
sml::Identifier* pCommand3 = agent->GetCommand(2) ;
no_agent_assertTrue(std::string(pCommand1->GetCommandName()) == "move"
|| std::string(pCommand2->GetCommandName()) == "move"
|| std::string(pCommand3->GetCommandName()) == "move");
no_agent_assertTrue(std::string(pCommand1->GetCommandName()) == "alternative"
|| std::string(pCommand2->GetCommandName()) == "alternative"
|| std::string(pCommand3->GetCommandName()) == "alternative");
no_agent_assertTrue(std::string(pCommand1->GetCommandName()) == "A"
|| std::string(pCommand2->GetCommandName()) == "A"
|| std::string(pCommand3->GetCommandName()) == "A");
if (m_Options.verbose)
{
std::cout << "Marking command as completed." << std::endl ;
}
pMove->AddStatusComplete();
no_agent_assertTrue(agent->Commit());
// The move command should be deleted in response to the
// the status complete getting added
agent->RunSelf(2) ;
no_agent_assertTrue_msg("RunSelf", agent->GetLastCommandLineResult());
// Dump out the output link again.
//if (agent->GetOutputLink())
//{
// printWMEs(agent->GetOutputLink()) ;
//}
// Test that we can interrupt a run by registering a handler that
// interrupts Soar immediately after a decision cycle.
// Removed the test part for now. Stats doesn't report anything.
bool interruptHandlerReceived(false);
int callback3 = agent->RegisterForRunEvent(sml::smlEVENT_AFTER_DECISION_CYCLE, Handlers::MyInterruptHandler, &interruptHandlerReceived) ;
agent->InitSoar();
no_agent_assertTrue_msg("init-soar", agent->GetLastCommandLineResult());
agent->RunSelf(20) ;
no_agent_assertTrue_msg("RunSelf", agent->GetLastCommandLineResult());
no_agent_assertTrue(interruptHandlerReceived);
interruptHandlerReceived = false;
//no_agent_assertTrue( agent->ExecuteCommandLine("stats") );
//std::string stats( agent->ExecuteCommandLine("stats") );
//no_agent_assertTrue_msg( "stats", agent->GetLastCommandLineResult() );
//size_t pos = stats.find( "1 decision cycles" ) ;
/*
if (pos == std::string.npos)
{
std::cout << "*** ERROR: Failed to interrupt Soar during a run." << std::endl ;
return false ;
}
*/
no_agent_assertTrue(agent->UnregisterForRunEvent(callback3));
/* These comments haven't kept up with the test -- does a lot more now
std::cout << std::endl << "If this test worked should see something like this (above here):" << std::endl ;
std::cout << "Top Identifier I3" << std::endl << "(I3 ^move M1)" << std::endl << "(M1 ^row 1)" << std::endl ;
std::cout << "(M1 ^col 1)" << std::endl << "(I3 ^alternative M1)" << std::endl ;
std::cout << "And then after the command is marked as completed (during the test):" << std::endl ;
std::cout << "Top Identifier I3" << std::endl ;
std::cout << "Together with about 6 received events" << std::endl ;
*/
no_agent_assertTrue(agent->UnregisterForRunEvent(callback1));
no_agent_assertTrue(agent->UnregisterForRunEvent(callback2));
no_agent_assertTrue(agent->UnregisterForRunEvent(callback_run_count));
SoarHelper::init_check_to_find_refcount_leaks(agent);
}
void FullTests_Parent::testSimpleCopy()
{
agent->SetOutputLinkChangeTracking(true);
loadProductions(SoarHelper::GetResource("testcopy.soar"));
/* Input structure for the test
(S1 ^io I1)
(I1 ^input-link I3)
(I3 ^sentence S2)
(S2 ^newest yes ^num-words 3 ^sentence-num 1 ^word W1 ^word W2 ^word W3)
(W1 ^num-word 1 ^word the)
(W2 ^num-word 2 ^word cat)
(W3 ^num-word 3 ^word in)
*/
sml::Identifier* map = agent->GetInputLink() ;
sml::Identifier* square2 = map->CreateIdWME("square");
no_agent_assertTrue(std::string(square2->GetAttribute()) == "square");
sml::Identifier* square5 = map->CreateIdWME("square");
no_agent_assertTrue(std::string(square5->GetAttribute()) == "square");
sml::Identifier* north = square2->CreateSharedIdWME("north", square5) ;
sml::Identifier* south = square5->CreateSharedIdWME("south", square2) ;
sml::Identifier* pSentence = agent->GetInputLink()->CreateIdWME("sentence") ;
no_agent_assertTrue(std::string(pSentence->GetAttribute()) == "sentence");
pSentence->CreateStringWME("newest", "ye s") ;
pSentence->CreateIntWME("num-words", 3) ;
sml::Identifier* pWord1 = pSentence->CreateIdWME("word") ;
no_agent_assertTrue(std::string(pWord1->GetAttribute()) == "word");
sml::Identifier* pWord5 = pSentence->CreateSharedIdWME("word2", pWord1) ;
no_agent_assertTrue(std::string(pWord5->GetAttribute()) == "word2");
sml::Identifier* pWord2 = pSentence->CreateIdWME("word") ;
no_agent_assertTrue(std::string(pWord2->GetAttribute()) == "word");
sml::Identifier* pWord3 = pSentence->CreateIdWME("word") ;
no_agent_assertTrue(std::string(pWord3->GetAttribute()) == "word");
pWord1->CreateIntWME("num-word", 1) ;
pWord2->CreateIntWME("num-word", 2) ;
pWord3->CreateIntWME("num-word", 3) ;
pWord1->CreateStringWME("word", "the") ;
pWord2->CreateStringWME("word", "cat") ;
pWord3->CreateStringWME("word", "in") ;
agent->Commit() ;
// Register for the trace output
std::stringstream trace ; // We'll pass this into the handler and build up the output in it