-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathtest_prologserver.py
1319 lines (1199 loc) · 55.2 KB
/
test_prologserver.py
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
import gc
import json
import logging
import os
from datetime import time
from tempfile import gettempdir, mkdtemp
import sys
import unittest
import threading
from time import sleep, perf_counter
from unittest import TestSuite
from swiplserver import *
from pathlib import PurePath, PurePosixPath, PureWindowsPath, Path
import subprocess
from contextlib import suppress
import tempfile
# From: https://eli.thegreenplace.net/2011/08/02/python-unit-testing-parametrized-test-cases/
class ParametrizedTestCase(unittest.TestCase):
"""TestCase classes that want to be parametrized should
inherit from this class.
"""
def __init__(
self,
methodName="runTest",
essentialOnly=False,
launchServer=True,
useUnixDomainSocket=None,
serverPort=None,
password=None,
):
super(ParametrizedTestCase, self).__init__(methodName)
self.launchServer = launchServer
self.useUnixDomainSocket = useUnixDomainSocket
self.serverPort = serverPort
self.password = password
self.essentialOnly = essentialOnly
self.prologPath = os.getenv("PROLOG_PATH") if os.getenv("PROLOG_PATH") else None
self.prologArgs = prologArgs
@staticmethod
def parametrize(
testcase_klass,
essentialOnly=False,
test_item_name=None,
launchServer=True,
useUnixDomainSocket=None,
serverPort=None,
password=None,
):
"""Create a suite containing all tests taken from the given
subclass, passing them the parameter 'param'.
"""
testloader = unittest.TestLoader()
testnames = testloader.getTestCaseNames(testcase_klass)
suite = unittest.TestSuite()
if test_item_name is None:
for name in testnames:
suite.addTest(
testcase_klass(
name,
essentialOnly=essentialOnly,
launchServer=launchServer,
useUnixDomainSocket=useUnixDomainSocket,
serverPort=serverPort,
password=password,
)
)
else:
suite.addTest(
testcase_klass(
test_item_name,
essentialOnly=essentialOnly,
launchServer=launchServer,
useUnixDomainSocket=useUnixDomainSocket,
serverPort=serverPort,
password=password,
)
)
return suite
class TestPrologServer(ParametrizedTestCase):
def setUp(self):
self.initialProcessCount = self.process_count("swipl")
def tearDown(self):
# Make sure we aren't leaving processes around
# Give the process a bit to exit
# Since this takes time, and won't work when running in SWI Prolog build process
# Turn it off if essentialOnly
if not essentialOnly:
count = 0
while count < 5:
currentCount = self.process_count("swipl")
if currentCount == self.initialProcessCount:
break
else:
sleep(2)
count += 1
self.assertEqual(currentCount, self.initialProcessCount)
# If we're using a Unix Domain Socket, make sure the file was cleaned up
self.assertTrue(
self.useUnixDomainSocket is None
or not os.path.exists(self.useUnixDomainSocket)
)
def process_count(self, process_name):
if os.name == "nt":
call = "TASKLIST", "/FI", "imagename eq %s" % process_name + ".exe"
# use buildin check_output right away
output = subprocess.check_output(call).decode()
# check each line for process name
count = 0
for line in output.strip().split("\r\n"):
if line.lower().startswith(process_name.lower()):
count += 1
return count
else:
with subprocess.Popen(
["pgrep", process_name], stdout=subprocess.PIPE
) as process:
data = process.stdout.readlines()
return len(data)
def thread_failure_reason(self, client, threadID, secondsTimeout):
count = 0
while True:
assert count < secondsTimeout
# Thread has exited if thread_property(GoalID, status(PropertyGoal)) and PropertyGoal \== running OR if we get an exception (meaning the thread is gone)
result = client.query(
"GoalID = {}, once((\\+ is_thread(GoalID) ; catch(thread_property(GoalID, status(PropertyGoal)), Exception, true), once(((var(Exception), PropertyGoal \\== running) ; nonvar(Exception)))))".format(
threadID
)
)
if result is False:
count += 1
sleep(1)
else:
# If the thread was aborted keep trying since it will spuriously appear and then disappear
reason = result[0]["PropertyGoal"]
# Should be this but - Workaround SWI Prolog bug: https://github.com/SWI-Prolog/swipl-devel/issues/852
# Joining crashes Prolog in the way the code joins and so we will have extra threads that have exited reported by thread_property
# just treat them as gone
# if prolog_name(reason) == "exception" and prolog_args(reason)[0] == "$aborted":
# continue
# else:
# return reason
if (
prolog_name(reason) == "exception"
and prolog_args(reason)[0] == "$aborted"
):
return "_"
else:
return reason
# Wait for the threads to exit and return the reason for exit
# will be "_" if they exited in an expected way
def thread_failure_reasons(self, client, threadIDList, secondsTimeout):
reasons = []
for threadID in threadIDList:
reason = self.thread_failure_reason(client, threadID, secondsTimeout)
reasons.append(reason)
return reasons
def assertThreadExitExpected(self, client, threadIDList, timeout):
reasonList = self.thread_failure_reasons(client, threadIDList, timeout)
for reason in reasonList:
# They should exit in an expected way
self.assertEqual(reason, "_")
def thread_list(self, prologThread):
result = prologThread.query("thread_property(ThreadID, status(Status))")
testThreads = []
for item in result:
# Should be this but - Workaround SWI Prolog bug: https://github.com/SWI-Prolog/swipl-devel/issues/852
# Joining crashes Prolog in the way the code joins and so we will have extra threads that have exited reported by thread_property
# just treat them as gone
# testThreads.append(item["ThreadID"] + ":" + str(item["Status"]))
if prolog_name(item["Status"]) == "true" or (
prolog_name(item["Status"]) == "exception"
and prolog_args(item["Status"])[0] == "$aborted"
):
continue
else:
testThreads.append(item["ThreadID"] + ":" + str(item["Status"]))
return testThreads
def round_trip_prolog(self, client, testTerm, expectedText=None):
if expectedText is None:
expectedText = testTerm
result = client.query(f"X = {testTerm}")
term = result[0]["X"]
convertedTerm = json_to_prolog(term)
assert convertedTerm == expectedText
def sync_query_timeout(self, prologThread, sleepForSeconds, queryTimeout):
# Query that times out")
caughtException = False
try:
result = prologThread.query(
f"sleep({sleepForSeconds})", query_timeout_seconds=queryTimeout
)
except PrologQueryTimeoutError as error:
caughtException = True
assert caughtException
def async_query_timeout(self, prologThread, sleepForSeconds, queryTimeout):
# async query with all results that times out on second of three results")
prologThread.query_async(
f"(member(X, [Y=a, sleep({sleepForSeconds}), Y=b]), X)",
query_timeout_seconds=queryTimeout,
)
try:
result = prologThread.query_async_result()
except PrologQueryTimeoutError as error:
caughtException = True
assert caughtException
# Calling cancel after the goal times out after one successful iteration")
prologThread.query_async(
f"(member(X, [Y=a, sleep({sleepForSeconds}), Y=b]), X)",
query_timeout_seconds=queryTimeout,
find_all=False,
)
sleep(sleepForSeconds + 1)
prologThread.cancel_query_async()
results = []
while True:
try:
result = prologThread.query_async_result()
except PrologQueryTimeoutError as error:
results.append("time_limit_exceeded")
break
if result is None:
break
results.append(result)
self.assertEqual(
[
[{"X": {"args": ["a", "a"], "functor": "="}, "Y": "a"}],
"time_limit_exceeded",
],
results,
)
def test_json_to_prolog(self):
with PrologServer(
self.launchServer,
self.serverPort,
self.password,
self.useUnixDomainSocket,
prolog_path=self.prologPath,
) as server:
with server.create_thread() as client:
# Test non-quoted terms
self.round_trip_prolog(client, "a")
self.round_trip_prolog(client, "1")
self.round_trip_prolog(client, "1.1")
self.round_trip_prolog(client, "a(b)")
self.round_trip_prolog(client, "a(b, c)")
self.round_trip_prolog(client, "[a(b)]")
self.round_trip_prolog(client, "[a(b), b(c)]")
self.round_trip_prolog(client, "[a(b(d)), b(c)]")
self.round_trip_prolog(client, "[2, 1.1]")
# Test variables
self.round_trip_prolog(client, "[_1, _a, Auto]", "[A, B, C]")
self.round_trip_prolog(client, "_")
self.round_trip_prolog(client, "_1", "A")
self.round_trip_prolog(client, "_1a", "A")
# Test quoting terms
# Terms that do not need to be quoted round trip without quoting")
self.round_trip_prolog(client, "a('b')", "a(b)")
self.round_trip_prolog(client, "a('_')", "a(_)")
# These terms all need quoting
self.round_trip_prolog(client, "a('b A')")
self.round_trip_prolog(client, "a('1b')")
self.round_trip_prolog(client, "'a b'(['1b', 'a b'])")
def test_sync_query(self):
with PrologServer(
self.launchServer,
self.serverPort,
self.password,
self.useUnixDomainSocket,
prolog_path=self.prologPath,
) as server:
with server.create_thread() as client:
# Most basic query with single answer and no free variables
result = client.query("atom(a)")
assert True is result
# Most basic query with multiple answers and no free variables
client.query(
"(retractall(noFreeVariablesMultipleResults), assert((noFreeVariablesMultipleResults :- member(_, [1, 2, 3]))))"
)
result = client.query("noFreeVariablesMultipleResults")
assert [True, True, True] == result
# Most basic query with single answer and two free variables
client.query(
"(retractall(twoFreeVariablesOneResult(X, Y)), assert((twoFreeVariablesOneResult(X, Y) :- X = 1, Y = 1)))"
)
result = client.query("twoFreeVariablesOneResult(X, Y)")
assert [{"X": 1, "Y": 1}] == result
# Most basic query with multiple answers and two free variables
client.query(
"(retractall(twoFreeVariablesMultipleResults(X, Y)), assert((twoFreeVariablesMultipleResults(X, Y) :- member(X-Y, [1-1, 2-2, 3-3]))))"
)
result = client.query("twoFreeVariablesMultipleResults(X, Y)")
assert [{"X": 1, "Y": 1}, {"X": 2, "Y": 2}, {"X": 3, "Y": 3}] == result
# Query that that has a parse error
caughtException = False
try:
result = client.query("member(X, [first, second, third]")
except PrologError as error:
assert error.is_prolog_exception("syntax_error")
caughtException = True
assert caughtException
self.sync_query_timeout(client, sleepForSeconds=3, queryTimeout=1)
# Query that throws
caughtException = False
try:
result = client.query("throw(test)")
except PrologError as error:
assert error.is_prolog_exception("test")
caughtException = True
assert caughtException
def test_sync_query_slow(self):
if self.essentialOnly:
print("skipped")
return
with PrologServer(
self.launchServer,
self.serverPort,
self.password,
self.useUnixDomainSocket,
prolog_path=self.prologPath,
) as server:
with server.create_thread() as client:
# query that is long enough to send heartbeats but eventually succeeds
self.assertTrue(client.query("sleep(5)"))
self.assertGreater(client._heartbeat_count, 0)
def test_async_query(self):
with PrologServer(
self.launchServer,
self.serverPort,
self.password,
self.useUnixDomainSocket,
prolog_path=self.prologPath,
) as server:
with server.create_thread() as client:
# Cancelling while nothing is happening should throw
caughtException = False
try:
client.cancel_query_async()
except PrologNoQueryError as error:
assert error.is_prolog_exception("no_query")
caughtException = True
assert caughtException
# Getting a result when no query running should throw
caughtException = False
try:
client.query_async_result()
except PrologNoQueryError as error:
assert error.is_prolog_exception("no_query")
caughtException = True
assert caughtException
##########
# Async queries with all results
##########
# Most basic async query with all results and no free variables
client.query_async("atom(a)", find_all=True)
result = client.query_async_result()
assert True == result
# async query with all results and free variables
client.query_async("member(X, [first, second, third])")
result = client.query_async_result()
assert [{"X": "first"}, {"X": "second"}, {"X": "third"}] == result
# async query with all results that gets cancelled while goal is executing
client.query_async("(member(X, [Y=a, sleep(3), Y=b]), X)")
client.cancel_query_async()
try:
result = client.query_async_result()
except PrologQueryCancelledError as error:
assert error.is_prolog_exception("cancel_goal")
caughtException = True
assert caughtException
# async query with all results that throws
client.query_async("throw(test)")
try:
result = client.query_async_result()
except PrologError as error:
assert error.is_prolog_exception("test")
caughtException = True
assert caughtException
##########
# Async queries with individual results
##########
# async query that has a parse error
query = "member(X, [first, second, third]"
caughtException = False
try:
client.query_async(query)
except PrologError as error:
assert error.is_prolog_exception("syntax_error")
caughtException = True
assert caughtException
# an async query with multiple results as individual results
client.query_async("member(X, [first, second, third])", find_all=False)
results = []
while True:
result = client.query_async_result()
if result is None:
break
results.append(result[0])
assert [{"X": "first"}, {"X": "second"}, {"X": "third"}] == results
# Async query with individual results that times out on second of three results
client.query_async(
"(member(X, [Y=a, sleep(3), Y=b]), X)",
query_timeout_seconds=1,
find_all=False,
)
results = []
while True:
try:
result = client.query_async_result()
except PrologError as error:
results.append(error.prolog())
break
if result is None:
break
results.append(result[0])
assert [
{"X": {"args": ["a", "a"], "functor": "="}, "Y": "a"},
"time_limit_exceeded",
] == results
# Async query that is cancelled after retrieving first result but while the query is running
client.query_async(
"(member(X, [Y=a, sleep(3), Y=b]), X)", find_all=False
)
result = client.query_async_result()
assert [{"X": {"args": ["a", "a"], "functor": "="}, "Y": "a"}] == result
client.cancel_query_async()
try:
result = client.query_async_result()
except PrologQueryCancelledError as error:
assert error.is_prolog_exception("cancel_goal")
caughtException = True
assert caughtException
# Calling cancel after the goal is finished and results have been retrieved
client.query_async("(member(X, [Y=a, Y=b, Y=c]), X)", find_all=True)
sleep(1)
result = client.query_async_result()
assert [
{"X": {"args": ["a", "a"], "functor": "="}, "Y": "a"},
{"X": {"args": ["b", "b"], "functor": "="}, "Y": "b"},
{"X": {"args": ["c", "c"], "functor": "="}, "Y": "c"},
] == result
caughtException = False
try:
client.cancel_query_async()
except PrologNoQueryError as error:
assert error.is_prolog_exception("no_query")
caughtException = True
assert caughtException
# async query with separate results that throws
client.query_async("throw(test)", find_all=False)
try:
result = client.query_async_result()
except PrologError as error:
assert error.is_prolog_exception("test")
caughtException = True
assert caughtException
def test_async_query_slow(self):
if self.essentialOnly:
print("skipped")
return
with PrologServer(
self.launchServer,
self.serverPort,
self.password,
self.useUnixDomainSocket,
prolog_path=self.prologPath,
) as server:
with server.create_thread() as client:
# Async query that checks for second result before it is available
client.query_async(
"(member(X, [Y=a, sleep(3), Y=b]), X)",
query_timeout_seconds=10,
find_all=False,
)
results = []
resultNotAvailable = False
while True:
try:
result = client.query_async_result(0)
if result is None:
break
else:
results.append(result[0])
except PrologResultNotAvailableError as error:
resultNotAvailable = True
assert (
resultNotAvailable
and [
{"X": {"args": ["a", "a"], "functor": "="}, "Y": "a"},
{"X": {"args": [3], "functor": "sleep"}, "Y": "_"},
{"X": {"args": ["b", "b"], "functor": "="}, "Y": "b"},
]
== results
)
self.async_query_timeout(client, 3, 1)
def test_protocol_edge_cases(self):
if self.essentialOnly:
print("skipped")
return
with PrologServer(
self.launchServer,
self.serverPort,
self.password,
self.useUnixDomainSocket,
prolog_path=self.prologPath,
) as server:
with server.create_thread() as client:
# Call two async queries in a row. Should work and return the second results at least 1 heartbeat should be sent
# in the response
client.query_async(
"(member(X, [Y=a, Y=b, Y=c]), X), sleep(3)", find_all=False
)
client.query_async("(member(X, [Y=d, Y=e, Y=f]), X)", find_all=False)
self.assertGreater(client._heartbeat_count, 0)
results = []
while True:
result = client.query_async_result()
if result is None:
break
results.append(result[0])
assert [
{"X": {"args": ["d", "d"], "functor": "="}, "Y": "d"},
{"X": {"args": ["e", "e"], "functor": "="}, "Y": "e"},
{"X": {"args": ["f", "f"], "functor": "="}, "Y": "f"},
] == results
# Call sync while async is pending, should work and return sync call results
client.query_async("(member(X, [Y=a, Y=b, Y=c]), X)", find_all=False)
results = client.query("(member(X, [Y=d, Y=e, Y=f]), X)")
assert [
{"X": {"args": ["d", "d"], "functor": "="}, "Y": "d"},
{"X": {"args": ["e", "e"], "functor": "="}, "Y": "e"},
{"X": {"args": ["f", "f"], "functor": "="}, "Y": "f"},
] == results
def test_connection_close_with_running_query(self):
if self.essentialOnly:
print("skipped")
return
with PrologServer(
self.launchServer,
self.serverPort,
self.password,
self.useUnixDomainSocket,
prolog_path=self.prologPath,
) as server:
with server.create_thread() as monitorThread:
# Closing a connection with an synchronous query running should abort the query and terminate the threads expectedly
with server.create_thread() as prologThread:
# Run query in a thread since it is synchronous and we want to cancel before finished
def TestThread(prologThread):
with suppress(Exception):
prologThread.query(
"(sleep(10), assert(closeConnectionTestFinished)"
)
thread = threading.Thread(target=TestThread, args=(prologThread,))
thread.start()
# Give it time to start
sleep(1)
# Close the connection while running
prologThread.stop()
thread.join()
self.assertThreadExitExpected(
monitorThread,
[
prologThread.goal_thread_id,
prologThread.communication_thread_id,
],
5,
)
# Make sure it didn't finish
exceptionCaught = False
try:
monitorThread.query("closeConnectionTestFinished")
except PrologError as error:
exceptionCaught = True
assert error.is_prolog_exception("existence_error")
# Closing a connection with an asynchronous query running should abort the query and terminate the threads expectedly
with server.create_thread() as prologThread:
prologThread.query_async(
"(sleep(10), assert(closeConnectionTestFinished))"
)
# Give it time to start the goal
sleep(1)
# left "with" clause so connection is closed, query should be cancelled
self.assertThreadExitExpected(
monitorThread,
[prologThread.goal_thread_id, prologThread.communication_thread_id],
5,
)
# Make sure it didn't finish
exceptionCaught = False
try:
monitorThread.query("closeConnectionTestFinished")
except PrologError as error:
exceptionCaught = True
assert error.is_prolog_exception("existence_error")
# To prove that threads are running concurrently have them all assert something then wait
# Then release the mutex
# then check to see if they all finished
def test_multiple_connections(self):
if self.essentialOnly:
print("skipped")
return
with PrologServer(
self.launchServer,
self.serverPort,
self.password,
self.useUnixDomainSocket,
prolog_path=self.prologPath,
) as server:
with server.create_thread() as monitorThread:
with server.create_thread() as controlThread:
# Will keep the mutex since the thread is kept alive
try:
controlThread.query(
"mutex_create(test), mutex_lock(test), assert(started(-1)), assert(ended(-1))"
)
prologThreads = []
for index in range(0, 5):
prologThread = server.create_thread()
prologThread.start()
prologThread.query_async(
f"assert({'started(' + str(index) + ')'}), with_mutex(test, assert({'ended(' + str(index) + ')'}))"
)
prologThreads.append(prologThread)
# Give time to get to mutex
sleep(3)
# now make sure they all started but didn't end since the mutex hasn't been released
startResult = monitorThread.query(
"findall(Value, started(Value), StartedList), findall(Value, ended(Value), EndedList)"
)
startedList = startResult[0]["StartedList"]
endedList = startResult[0]["EndedList"]
self.assertEqual(startedList.sort(), [-1, 0, 1, 2, 3, 4].sort())
self.assertEqual(endedList, [-1])
# release the mutex and delete the data
controlThread.query("mutex_unlock(test)")
# They should have ended now
startResult = monitorThread.query(
"findall(Value, ended(Value), EndedList)"
)
endedList = startResult[0]["EndedList"]
self.assertEqual(endedList.sort(), [-1, 0, 1, 2, 3, 4].sort())
finally:
# and destroy it
controlThread.query(
"mutex_destroy(test), retractall(ended(_)), retractall(started(_))"
)
def test_multiple_serial_connections(self):
# Multiple connections can run serially
with PrologServer(
self.launchServer,
self.serverPort,
self.password,
self.useUnixDomainSocket,
prolog_path=self.prologPath,
) as server:
with server.create_thread() as prologThread:
result = prologThread.query("true")
self.assertEqual(result, True)
sleep(1)
with server.create_thread() as prologThread:
result = prologThread.query("true")
self.assertEqual(result, True)
sleep(1)
with server.create_thread() as prologThread:
result = prologThread.query("true")
self.assertEqual(result, True)
def test_goal_thread_failure(self):
# If the goal thread fails, we should get a specific exception and the thread should be left for inspection
with PrologServer(
self.launchServer,
self.serverPort,
self.password,
self.useUnixDomainSocket,
prolog_path=self.prologPath,
) as server:
with server.create_thread() as prologThread:
# Force the goal thread to throw outside of the "safe zone" and shutdown unexpectedly
prologThread._send("testThrowGoalThread(test_exception).\n")
result = prologThread._receive()
# give it time to process
sleep(2)
# The next query should get a final exception
exceptionHandled = False
try:
result = prologThread.query("true")
except PrologConnectionFailedError as error:
assert error.is_prolog_exception("connection_failed")
exceptionHandled = True
assert exceptionHandled
# At this point the server communication thread has failed and stopped the server since we launched with
# haltOnCommunicationFailure(true), so this should fail. Finding a reliable way to detect if the process is gone
# that works cross platform was very hard. The alternative which is to try to connect and fail after a timeout
# was surprisingly also hard. So, for now, we're not verifying that.
def test_quit(self):
# Sending quit should shutdown the server")
with PrologServer(
self.launchServer,
self.serverPort,
self.password,
self.useUnixDomainSocket,
prolog_path=self.prologPath,
) as server:
with server.create_thread() as prologThread:
prologThread.halt_server()
# Finding a reliable way to detect if the process is gone
# that works cross platform was very hard. The alternative which is to try to connect and fail after a timeout
# was surprisingly also hard. So, for now, we're not verifying that.
def test_unknown_command(self):
# Sending an unknown command should throw")
with PrologServer(
self.launchServer,
self.serverPort,
self.password,
self.useUnixDomainSocket,
prolog_path=self.prologPath,
) as server:
with server.create_thread() as prologThread:
# Force the goal thread to throw outside of the "safe zone" and shutdown unexpectedly
prologThread._send("foo.\n")
result = json.loads(prologThread._receive())
assert (
prolog_name(result) == "exception"
and prolog_name(prolog_args(result)[0]) == "unknownCommand"
)
def test_server_options_and_shutdown(self):
with PrologServer(
self.launchServer,
self.serverPort,
self.password,
self.useUnixDomainSocket,
prolog_path=self.prologPath,
) as server:
with server.create_thread() as monitorThread:
# Record the threads that are running, but give a pause so any threads created by the server on startup
# can get closed down
initialThreads = self.thread_list(monitorThread)
socketPort = 4250
# password() should be used if supplied.
result = monitorThread.query(
"language_server([port(Port), password(testpassword), server_thread(ServerThreadID)])"
)
serverThreadID = result[0]["ServerThreadID"]
port = result[0]["Port"]
with PrologServer(
launch_server=False,
port=port,
password="testpassword",
prolog_path=self.prologPath,
) as newServer:
with newServer.create_thread() as prologThread:
result = prologThread.query("true")
self.assertEqual(result, True)
result = monitorThread.query(f"stop_language_server({serverThreadID})")
self.assertEqual(result, True)
afterShutdownThreads = self.thread_list(monitorThread)
self.assertEqual(afterShutdownThreads, initialThreads)
if os.name != "nt":
# unixDomainSocket() should be used if supplied (non-windows).
socketPath = mkdtemp()
unixDomainSocket = PrologServer.unix_domain_socket_file(socketPath)
result = monitorThread.query(
f"language_server([unix_domain_socket('{unixDomainSocket}'), password(testpassword), server_thread(ServerThreadID)])"
)
serverThreadID = result[0]["ServerThreadID"]
with PrologServer(
launch_server=False,
unix_domain_socket=unixDomainSocket,
password="testpassword",
prolog_path=self.prologPath,
) as newServer:
with newServer.create_thread() as prologThread:
result = prologThread.query("true")
self.assertEqual(result, True)
result = monitorThread.query(
f"stop_language_server({serverThreadID})"
)
self.assertEqual(result, True)
afterShutdownThreads = self.thread_list(monitorThread)
self.assertEqual(afterShutdownThreads, initialThreads)
assert not os.path.exists(unixDomainSocket)
# unixDomainSocket() should be generated if asked for (non-windows).
result = monitorThread.query(
"language_server([unix_domain_socket(Socket), password(testpassword), server_thread(ServerThreadID)])"
)
serverThreadID = result[0]["ServerThreadID"]
unixDomainSocket = result[0]["Socket"]
with PrologServer(
launch_server=False,
unix_domain_socket=unixDomainSocket,
password="testpassword",
prolog_path=self.prologPath,
) as newServer:
with newServer.create_thread() as prologThread:
result = prologThread.query("true")
self.assertEqual(result, True)
result = monitorThread.query(
f"stop_language_server({serverThreadID})"
)
self.assertEqual(result, True)
afterShutdownThreads = self.thread_list(monitorThread)
self.assertEqual(afterShutdownThreads, initialThreads)
# Temp Socket should not exist
assert not os.path.exists(unixDomainSocket)
# Neither should Temp directory
assert not os.path.exists(Path(unixDomainSocket).parent)
# runServerOnThread(false) should block until the server is shutdown.
# Create a new connection that we block starting a new server
with server.create_thread() as blockedThread:
blockedThread.query_async(
"language_server([port({}), password(testpassword), run_server_on_thread(false), server_thread(testServerThread)])".format(
socketPort
)
)
# Wait for the server to start
sleep(1)
# Make sure we are still blocked
exceptionCaught = False
try:
blockedThread.query_async_result(wait_timeout_seconds=0)
except PrologResultNotAvailableError:
exceptionCaught = True
assert exceptionCaught
# Ensure the server started by sending it a query
with PrologServer(
launch_server=False,
port=socketPort,
password="testpassword",
prolog_path=self.prologPath,
) as newServer:
with newServer.create_thread() as prologThread:
result = prologThread.query("true")
self.assertEqual(result, True)
# Make sure we are still blocked
exceptionCaught = False
try:
blockedThread.query_async_result(wait_timeout_seconds=0)
except PrologResultNotAvailableError:
exceptionCaught = True
assert exceptionCaught
# Now shut it down by cancelling the query and running stop
blockedThread.cancel_query_async()
result = monitorThread.query(
f"stop_language_server({blockedThread.communication_thread_id})"
)
self.assertEqual(result, True)
# And make sure all the threads went away
count = 0
while count < 5:
afterShutdownThreads = self.thread_list(monitorThread)
if afterShutdownThreads == initialThreads:
break
else:
count += 1
if count == 5:
print(initialThreads)
print(afterShutdownThreads)
assert False
# Launching this library itself and stopping in the debugger tests writeConnectionValues() and ignoreSigint and haltOnConnectionFailure internal features automatically
def test_server_options_and_shutdown_slow(self):
if self.essentialOnly:
print("skipped")
return
with PrologServer(
self.launchServer,
self.serverPort,
self.password,
self.useUnixDomainSocket,
prolog_path=self.prologPath,
) as server:
with server.create_thread() as monitorThread:
# Record the threads that are running, but give a pause so any threads created by the server on startup
# can get closed down
initialThreads = self.thread_list(monitorThread)
# When starting a server, some variables can be filled in with defaults. Also: only the server thread should be created
# Launch the new server with appropriate options specified with variables to make sure they get filled in
if os.name == "nt":
result = monitorThread.query(
"language_server([port(Port), server_thread(ServerThreadID), password(Password)])"
)
optionsDict = result[0]
assert (
"Port" in optionsDict
and "ServerThreadID" in optionsDict
and "Password" in optionsDict
)
else:
result = monitorThread.query(
"language_server([port(Port), server_thread(ServerThreadID), password(Password), unix_domain_socket(Unix)])"
)
optionsDict = result[0]
assert (
"Port" in optionsDict
and "ServerThreadID" in optionsDict
and "Password" in optionsDict
and "Unix" in optionsDict
)
# Get the new threadlist
result = monitorThread.query(
"thread_property(ThreadID, status(Status))"
)
testThreads = self.thread_list(monitorThread)
# Only a server thread should have been started
assert len(testThreads) - len(initialThreads) == 1
# stop_language_server should remove all (and only) created threads and the Unix Domain File (which is tested on self.tearDown())
result = monitorThread.query(
f"stop_language_server({optionsDict['ServerThreadID']})"
)
sleep(2)
afterShutdownThreads = self.thread_list(monitorThread)
self.assertEqual(afterShutdownThreads, initialThreads)
# queryTimeout() supplied at startup should apply to queries by default. password() and port() should be used if supplied.
socketPort = 4250
result = monitorThread.query(