-
Notifications
You must be signed in to change notification settings - Fork 13
/
plunit.pl
2618 lines (2269 loc) · 75.6 KB
/
plunit.pl
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
/* Part of SWI-Prolog
Author: Jan Wielemaker
E-mail: J.Wielemaker@vu.nl
WWW: http://www.swi-prolog.org
Copyright (c) 2006-2024, University of Amsterdam
VU University Amsterdam
CWI, Amsterdam
SWI-Prolog Solutions b.v.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
:- module(plunit,
[ set_test_options/1, % +Options
begin_tests/1, % +Name
begin_tests/2, % +Name, +Options
end_tests/1, % +Name
run_tests/0, % Run all tests
run_tests/1, % +Tests
run_tests/2, % +Tests, +Options
load_test_files/1, % +Options
running_tests/0, % Prints currently running test
current_test/5, % ?Unit,?Test,?Line,?Body,?Options
current_test_unit/2, % ?Unit,?Options
test_report/1 % +What
]).
/** <module> Unit Testing
Unit testing environment for SWI-Prolog and SICStus Prolog. For usage,
please visit https://www.swi-prolog.org/pldoc/package/plunit.
*/
:- autoload(library(statistics), [call_time/2]).
:- autoload(library(apply),
[maplist/3, include/3, maplist/2, foldl/4, partition/4]).
:- autoload(library(lists), [member/2, append/2, flatten/2, append/3]).
:- autoload(library(option), [ option/3, option/2, select_option/3 ]).
:- autoload(library(ordsets), [ord_intersection/3]).
:- autoload(library(error), [must_be/2, domain_error/2]).
:- autoload(library(aggregate), [aggregate_all/3]).
:- autoload(library(streams), [with_output_to/3]).
:- autoload(library(ansi_term), [ansi_format/3]).
:- if(exists_source(library(time))).
:- autoload(library(time), [call_with_time_limit/2]).
:- endif.
:- public
unit_module/2.
:- meta_predicate
valid_options(1, +),
count(0, -).
/*******************************
* CONDITIONAL COMPILATION *
*******************************/
swi :- catch(current_prolog_flag(dialect, swi), _, fail).
sicstus :- catch(current_prolog_flag(dialect, sicstus), _, fail).
throw_error(Error_term,Impldef) :-
throw(error(Error_term,context(Impldef,_))).
:- set_prolog_flag(generate_debug_info, false).
current_test_flag(optimise, Value) =>
current_prolog_flag(optimise, Value).
current_test_flag(occurs_check, Value) =>
( current_prolog_flag(plunit_occurs_check, Value0)
-> Value = Value0
; current_prolog_flag(occurs_check, Value)
).
current_test_flag(Name, Value), atom(Name) =>
atom_concat(plunit_, Name, Flag),
current_prolog_flag(Flag, Value).
current_test_flag(Name, Value), var(Name) =>
global_test_option(Opt, _, _Type, _Default),
functor(Opt, Name, 1),
current_test_flag(Name, Value).
set_test_flag(Name, Value) :-
Opt =.. [Name, Value],
global_test_option(Opt),
!,
atom_concat(plunit_, Name, Flag),
set_prolog_flag(Flag, Value).
set_test_flag(Name, _) :-
domain_error(test_flag, Name).
current_test_flags(Flags) :-
findall(Flag, current_test_flag(Flag), Flags).
current_test_flag(Opt) :-
current_test_flag(Name, Value),
Opt =.. [Name, Value].
% ensure expansion to avoid tracing
goal_expansion(forall(C,A),
\+ (C, \+ A)).
goal_expansion(current_module(Module,File),
module_property(Module, file(File))).
/*******************************
* IMPORTS *
*******************************/
:- initialization init_flags.
init_flags :-
( global_test_option(Option, _Value, Type, Default),
Default \== (-),
Option =.. [Name,_],
atom_concat(plunit_, Name, Flag),
flag_type(Type, FlagType),
create_prolog_flag(Flag, Default, [type(FlagType), keep(true)]),
fail
; true
).
flag_type(boolean, FlagType) => FlagType = boolean.
flag_type(Type, FlagType), Type = oneof(Atoms), maplist(atom, Atoms) =>
FlagType = Type.
flag_type(oneof(_), FlagType) => FlagType = term.
flag_type(positive_integer, FlagType) => FlagType = integer.
flag_type(number, FlagType) => FlagType = float.
%! set_test_options(+Options)
%
% Specifies how to deal with test suites. Defined options are:
%
% - load(+Load)
% Whether or not the tests must be loaded. Values are
% `never`, `always`, `normal` (only if not optimised)
%
% - run(+When)
% When the tests are run. Values are `manual`, `make`
% or make(all).
%
% - format(+Mode)
% Currently one of `tty` or `log`. `tty` uses terminal
% control to overwrite successful tests, allowing the
% user to see the currently running tests and output
% from failed tests. This is the default of the output
% is a tty. `log` prints a full log of the executed
% tests and their result and is intended for non-interactive
% usage.
%
% - output(+When)
% If `always`, emit all output as it is produced, if `never`,
% suppress all output and if `on_failure`, emit the output
% if the test fails.
%
% - show_blocked(+Bool)
% Show individual blocked tests during the report.
%
% - occurs_check(+Mode)
% Defines the default for the `occurs_check` flag during
% testing.
%
% - cleanup(+Bool)
% If `true` (default =false), cleanup report at the end
% of run_tests/1. Used to improve cooperation with
% memory debuggers such as dmalloc.
%
% - jobs(Num)
% Number of jobs to use for concurrent testing. Default
% is one, implying sequential testing.
%
% - timeout(+Seconds)
% Set timeout for each individual test. This acts as a
% default that may be overuled at the level of units or
% individual tests. A timeout of 0 or negative is handled
% as _inifinite_.
set_test_options(Options) :-
flatten([Options], List),
maplist(set_test_option, List).
set_test_option(sto(true)) =>
print_message(warning, plunit(sto(true))).
set_test_option(jobs(Jobs)) =>
must_be(positive_integer, Jobs),
set_test_option_flag(jobs(Jobs)).
set_test_option(Option),
compound(Option), global_test_option(Option) =>
set_test_option_flag(Option).
set_test_option(Option) =>
domain_error(option, Option).
global_test_option(Opt) :-
global_test_option(Opt, Value, Type, _Default),
must_be(Type, Value).
global_test_option(load(Load), Load, oneof([never,always,normal]), normal).
global_test_option(output(Cond), Cond, oneof([always,on_failure]), on_failure).
global_test_option(format(Feedback), Feedback, oneof([tty,log]), tty).
global_test_option(silent(Silent), Silent, boolean, false).
global_test_option(show_blocked(Blocked), Blocked, boolean, false).
global_test_option(run(When), When, oneof([manual,make,make(all)]), make).
global_test_option(occurs_check(Mode), Mode, oneof([false,true,error]), -).
global_test_option(cleanup(Bool), Bool, boolean, true).
global_test_option(jobs(Count), Count, positive_integer, 1).
global_test_option(timeout(Number), Number, number, 3600).
set_test_option_flag(Option) :-
Option =.. [Name, Value],
set_test_flag(Name, Value).
%! loading_tests
%
% True if tests must be loaded.
loading_tests :-
current_test_flag(load, Load),
( Load == always
-> true
; Load == normal,
\+ current_test_flag(optimise, true)
).
/*******************************
* MODULE *
*******************************/
:- dynamic
loading_unit/4, % Unit, Module, File, OldSource
current_unit/4, % Unit, Module, Context, Options
test_file_for/2. % ?TestFile, ?PrologFile
%! begin_tests(+UnitName:atom) is det.
%! begin_tests(+UnitName:atom, Options) is det.
%
% Start a test-unit. UnitName is the name of the test set. the
% unit is ended by :- end_tests(UnitName).
begin_tests(Unit) :-
begin_tests(Unit, []).
begin_tests(Unit, Options) :-
must_be(atom, Unit),
map_sto_option(Options, Options1),
valid_options(test_set_option, Options1),
make_unit_module(Unit, Name),
source_location(File, Line),
begin_tests(Unit, Name, File:Line, Options1).
map_sto_option(Options0, Options) :-
select_option(sto(Mode), Options0, Options1),
!,
map_sto(Mode, Flag),
Options = [occurs_check(Flag)|Options1].
map_sto_option(Options, Options).
map_sto(rational_trees, Flag) => Flag = false.
map_sto(finite_trees, Flag) => Flag = true.
map_sto(Mode, _) => domain_error(sto, Mode).
:- if(swi).
begin_tests(Unit, Name, File:Line, Options) :-
loading_tests,
!,
'$set_source_module'(Context, Context),
( current_unit(Unit, Name, Context, Options)
-> true
; retractall(current_unit(Unit, Name, _, _)),
assert(current_unit(Unit, Name, Context, Options))
),
'$set_source_module'(Old, Name),
'$declare_module'(Name, test, Context, File, Line, false),
discontiguous(Name:'unit test'/4),
'$set_predicate_attribute'(Name:'unit test'/4, trace, false),
discontiguous(Name:'unit body'/2),
asserta(loading_unit(Unit, Name, File, Old)).
begin_tests(Unit, Name, File:_Line, _Options) :-
'$set_source_module'(Old, Old),
asserta(loading_unit(Unit, Name, File, Old)).
:- else.
% we cannot use discontiguous as a goal in SICStus Prolog.
user:term_expansion((:- begin_tests(Set)),
[ (:- begin_tests(Set)),
(:- discontiguous(test/2)),
(:- discontiguous('unit body'/2)),
(:- discontiguous('unit test'/4))
]).
begin_tests(Unit, Name, File:_Line, Options) :-
loading_tests,
!,
( current_unit(Unit, Name, _, Options)
-> true
; retractall(current_unit(Unit, Name, _, _)),
assert(current_unit(Unit, Name, -, Options))
),
asserta(loading_unit(Unit, Name, File, -)).
begin_tests(Unit, Name, File:_Line, _Options) :-
asserta(loading_unit(Unit, Name, File, -)).
:- endif.
%! end_tests(+Name) is det.
%
% Close a unit-test module.
%
% @tbd Run tests/clean module?
% @tbd End of file?
end_tests(Unit) :-
loading_unit(StartUnit, _, _, _),
!,
( Unit == StartUnit
-> once(retract(loading_unit(StartUnit, _, _, Old))),
'$set_source_module'(_, Old)
; throw_error(context_error(plunit_close(Unit, StartUnit)), _)
).
end_tests(Unit) :-
throw_error(context_error(plunit_close(Unit, -)), _).
%! make_unit_module(+Name, -ModuleName) is det.
%! unit_module(+Name, -ModuleName) is det.
:- if(swi).
unit_module(Unit, Module) :-
atom_concat('plunit_', Unit, Module).
make_unit_module(Unit, Module) :-
unit_module(Unit, Module),
( current_module(Module),
\+ current_unit(_, Module, _, _),
predicate_property(Module:H, _P),
\+ predicate_property(Module:H, imported_from(_M))
-> throw_error(permission_error(create, plunit, Unit),
'Existing module')
; true
).
:- else.
:- dynamic
unit_module_store/2.
unit_module(Unit, Module) :-
unit_module_store(Unit, Module),
!.
make_unit_module(Unit, Module) :-
prolog_load_context(module, Module),
assert(unit_module_store(Unit, Module)).
:- endif.
/*******************************
* EXPANSION *
*******************************/
%! expand_test(+Name, +Options, +Body, -Clause) is det.
%
% Expand test(Name, Options) :- Body into a clause for
% 'unit test'/4 and 'unit body'/2.
expand_test(Name, Options0, Body,
[ 'unit test'(Name, Line, Options, Module:'unit body'(Id, Vars)),
('unit body'(Id, Vars) :- !, Body)
]) :-
source_location(_File, Line),
prolog_load_context(module, Module),
( prolog_load_context(variable_names, Bindings)
-> true
; Bindings = []
),
atomic_list_concat([Name, '@line ', Line], Id),
term_variables(Options0, OptionVars0), sort(OptionVars0, OptionVars),
term_variables(Body, BodyVars0), sort(BodyVars0, BodyVars),
ord_intersection(OptionVars, BodyVars, VarList),
Vars =.. [vars|VarList],
( is_list(Options0) % allow for single option without list
-> Options1 = Options0
; Options1 = [Options0]
),
maplist(expand_option(Bindings), Options1, Options2),
join_true_options(Options2, Options3),
map_sto_option(Options3, Options4),
valid_options(test_option, Options4),
valid_test_mode(Options4, Options).
expand_option(_, Var, _) :-
var(Var),
!,
throw_error(instantiation_error,_).
expand_option(Bindings, Cmp, true(Cond)) :-
cmp(Cmp),
!,
var_cmp(Bindings, Cmp, Cond).
expand_option(_, error(X), throws(error(X, _))) :- !.
expand_option(_, exception(X), throws(X)) :- !. % SICStus 4 compatibility
expand_option(_, error(F,C), throws(error(F,C))) :- !. % SICStus 4 compatibility
expand_option(_, true, true(true)) :- !.
expand_option(_, O, O).
cmp(_ == _).
cmp(_ = _).
cmp(_ =@= _).
cmp(_ =:= _).
var_cmp(Bindings, Expr, cmp(Name, Expr)) :-
arg(_, Expr, Var),
var(Var),
member(Name=V, Bindings),
V == Var,
!.
var_cmp(_, Expr, Expr).
join_true_options(Options0, Options) :-
partition(true_option, Options0, True, Rest),
True \== [],
!,
maplist(arg(1), True, Conds0),
flatten(Conds0, Conds),
Options = [true(Conds)|Rest].
join_true_options(Options, Options).
true_option(true(_)).
valid_test_mode(Options0, Options) :-
include(test_mode, Options0, Tests),
( Tests == []
-> Options = [true([true])|Options0]
; Tests = [_]
-> Options = Options0
; throw_error(plunit(incompatible_options, Tests), _)
).
test_mode(true(_)).
test_mode(all(_)).
test_mode(set(_)).
test_mode(fail).
test_mode(throws(_)).
%! expand(+Term, -Clauses) is semidet.
expand(end_of_file, _) :-
loading_unit(Unit, _, _, _),
!,
end_tests(Unit), % warn?
fail.
expand((:-end_tests(_)), _) :-
!,
fail.
expand(_Term, []) :-
\+ loading_tests.
expand((test(Name) :- Body), Clauses) :-
!,
expand_test(Name, [], Body, Clauses).
expand((test(Name, Options) :- Body), Clauses) :-
!,
expand_test(Name, Options, Body, Clauses).
expand(test(Name), _) :-
!,
throw_error(existence_error(body, test(Name)), _).
expand(test(Name, _Options), _) :-
!,
throw_error(existence_error(body, test(Name)), _).
:- multifile
system:term_expansion/2.
system:term_expansion(Term, Expanded) :-
( loading_unit(_, _, File, _)
-> source_location(ThisFile, _),
( File == ThisFile
-> true
; source_file_property(ThisFile, included_in(File, _))
),
expand(Term, Expanded)
).
/*******************************
* OPTIONS *
*******************************/
%! valid_options(:Pred, +Options) is det.
%
% Verify Options to be a list of valid options according to
% Pred.
%
% @error `type_error` or `instantiation_error`.
valid_options(Pred, Options) :-
must_be(list, Options),
verify_options(Options, Pred).
verify_options([], _).
verify_options([H|T], Pred) :-
( call(Pred, H)
-> verify_options(T, Pred)
; throw_error(domain_error(Pred, H), _)
).
valid_options(Pred, Options0, Options, Rest) :-
must_be(list, Options0),
partition(Pred, Options0, Options, Rest).
%! test_option(+Option) is semidet.
%
% True if Option is a valid option for test(Name, Options).
test_option(Option) :-
test_set_option(Option),
!.
test_option(true(_)).
test_option(fail).
test_option(throws(_)).
test_option(all(_)).
test_option(set(_)).
test_option(nondet).
test_option(fixme(_)).
test_option(forall(X)) :-
must_be(callable, X).
test_option(timeout(Seconds)) :-
must_be(number, Seconds).
%! test_option(+Option) is semidet.
%
% True if Option is a valid option for :- begin_tests(Name,
% Options).
test_set_option(blocked(X)) :-
must_be(ground, X).
test_set_option(condition(X)) :-
must_be(callable, X).
test_set_option(setup(X)) :-
must_be(callable, X).
test_set_option(cleanup(X)) :-
must_be(callable, X).
test_set_option(occurs_check(V)) :-
must_be(oneof([false,true,error]), V).
test_set_option(concurrent(V)) :-
must_be(boolean, V),
print_message(informational, plunit(concurrent)).
test_set_option(timeout(Seconds)) :-
must_be(number, Seconds).
/*******************************
* UTIL *
*******************************/
:- meta_predicate
reify_tmo(0, -, +),
reify(0, -),
capture_output(0,-),
capture_output(0,-,+),
got_messages(0,-).
%! reify_tmo(:Goal, -Result, +Options) is det.
:- if(current_predicate(call_with_time_limit/2)).
reify_tmo(Goal, Result, Options) :-
option(timeout(Time), Options),
Time > 0,
!,
reify(call_with_time_limit(Time, Goal), Result0),
( Result0 = throw(time_limit_exceeded)
-> Result = throw(time_limit_exceeded(Time))
; Result = Result0
).
:- endif.
reify_tmo(Goal, Result, _Options) :-
reify(Goal, Result).
%! reify(:Goal, -Result) is det.
%
% Call Goal and unify Result with one of `true`, `false` or
% `throw(E)`.
reify(Goal, Result) :-
( catch(Goal, E, true)
-> ( var(E)
-> Result = true
; Result = throw(E)
)
; Result = false
).
%! capture_output(:Goal, -Output) is semidet.
%! capture_output(:Goal, -Output, +Options) is semidet.
%
% @arg Output is a pair `Msgs-String`, where `Msgs` is a boolean that
% is true if there were messages that require a non-zero exit status
% and Output contains the output as a string.
capture_output(Goal, Output) :-
current_test_flag(output, OutputMode),
capture_output(Goal, Output, [output(OutputMode)]).
capture_output(Goal, Msgs-Output, Options) :-
option(output(How), Options, always),
( How == always
-> call(Goal),
Msgs = false % irrelavant
; with_output_to(string(Output), got_messages(Goal, Msgs),
[ capture([user_output, user_error]),
color(true)
])
).
%! got_messages(:Goal, -Result)
got_messages(Goal, Result) :-
( current_prolog_flag(on_warning, status)
; current_prolog_flag(on_error, status)
), !,
nb_delete(plunit_got_message),
setup_call_cleanup(
asserta(( user:thread_message_hook(_Term, Kind, _Lines) :-
got_message(Kind), fail), Ref),
Goal,
erase(Ref)),
( nb_current(plunit_got_message, true)
-> Result = true
; Result = false
).
got_messages(Goal, false) :-
call(Goal).
:- public got_message/1.
got_message(warning) :-
current_prolog_flag(on_warning, status), !,
nb_setval(plunit_got_message, true).
got_message(error) :-
current_prolog_flag(on_error, status), !,
nb_setval(plunit_got_message, true).
/*******************************
* RUNNING TOPLEVEL *
*******************************/
:- dynamic
output_streams/2, % Output, Error
test_count/1, % Count
passed/5, % Unit, Test, Line, Det, Time
failed/5, % Unit, Test, Line, Reason, Time
timeout/5, % Unit, Test, Line, Limit, Time
failed_assertion/7, % Unit, Test, Line, ALoc, STO, Reason, Goal
blocked/4, % Unit, Test, Line, Reason
fixme/5, % Unit, Test, Line, Reason, Status
running/5, % Unit, Test, Line, STO, Thread
forall_failures/2. % Nth, Failures
%! run_tests is semidet.
%! run_tests(+TestSet) is semidet.
%! run_tests(+TestSet, +Options) is semidet.
%
% Run tests and report about the results. The predicate run_tests/0
% runs all known tests that are not blocked. The predicate run_tests/1
% takes a specification of tests to run.
%
% The predicate run_tests/2 is synchronized. Concurrent testing may
% be achieved using the relevant options. See
% set_test_options/1. Options are passed to set_test_options/1. In
% addition the following options are processed:
%
% - summary(-Summary)
% Unify Summary do a dict holding the keys below. The value of
% these keys is an integer describing the number of tests. If
% this option is given, run_tests/2 does not fail if some tests
% failed.
%
% - total
% - passed
% - failed
% - timeout
% - blocked
%
% @arg TestSet is either a single specification or a list of
% specifications. Each single specification is either the name of a
% test-unit or a term <test-unit>:<test>, denoting a single test
% within a unit. If TestSet is `all`, all known tests are executed.
run_tests :-
run_tests(all).
run_tests(Set) :-
run_tests(Set, []).
run_tests(all, Options) :-
!,
findall(Unit, current_test_unit(Unit,_), Units),
run_tests(Units, Options).
run_tests(Set, Options) :-
valid_options(global_test_option, Options, Global, Rest),
current_test_flags(Old),
setup_call_cleanup(
set_test_options(Global),
( flatten([Set], List),
maplist(runnable_tests, List, Units),
with_mutex(plunit, run_tests_sync(Units, Rest))
),
set_test_options(Old)).
run_tests_sync(Units0, Options) :-
cleanup,
count_tests(Units0, Units, Count),
asserta(test_count(Count)),
save_output_state,
setup_call_cleanup(
setup_trap_assertions(Ref),
call_time(setup_jobs_and_run_units(Count, Units, Summary, Options),
Time),
report_and_cleanup(Ref, Time, Options)),
( option(summary(Summary), Options)
-> true
; test_summary_passed(Summary) % fail if some test failed
).
setup_jobs_and_run_units(Count, Units, Summary, Options) :-
setup_call_cleanup(
setup_jobs(Count),
( run_units(Units, Options),
test_summary(_All, Summary)
),
cleanup_jobs).
%! report_and_cleanup(+Ref, +Time, +Options)
%
% Undo changes to the environment (trapping assertions), report the
% results and cleanup.
report_and_cleanup(Ref, Time, Options) :-
cleanup_trap_assertions(Ref),
report(Time, Options),
cleanup_after_test.
%! run_units_and_check_errors(+Units, +Options) is semidet.
%
% Run all test units and succeed if all tests passed.
run_units(Units, _Options) :-
maplist(schedule_unit, Units),
job_wait(_).
%! runnable_tests(+Spec, -Plan) is det.
%
% Change a Unit+Test spec into a plain `Unit:Tests` lists, where
% blocked tests or tests whose condition fails are already removed.
% Each test in `Tests` is a term `@(Test,Line)`, which serves as a
% unique identifier of the test.
:- det(runnable_tests/2).
runnable_tests(Spec, Unit:RunnableTests) :-
unit_from_spec(Spec, Unit, Tests, Module, UnitOptions),
( option(blocked(Reason), UnitOptions)
-> info(plunit(blocked(unit(Unit, Reason)))),
RunnableTests = []
; \+ condition(Module, unit(Unit), UnitOptions)
-> RunnableTests = []
; var(Tests)
-> findall(TestID,
runnable_test(Unit, _Test, Module, TestID),
RunnableTests)
; flatten([Tests], TestList),
findall(TestID,
( member(Test, TestList),
runnable_test(Unit,Test,Module, TestID)
),
RunnableTests)
).
runnable_test(Unit, Name, Module, @(Test,Line)) :-
current_test(Unit, Name, Line, _Body, TestOptions),
( option(blocked(Reason), TestOptions)
-> Test = blocked(Name, Reason)
; condition(Module, test(Unit,Name,Line), TestOptions),
Test = Name
).
unit_from_spec(Unit0:Tests0, Unit, Tests, Module, Options), atom(Unit0) =>
Unit = Unit0,
Tests = Tests0,
( current_unit(Unit, Module, _Supers, Options)
-> true
; throw_error(existence_error(unit_test, Unit), _)
).
unit_from_spec(Unit0, Unit, _, Module, Options), atom(Unit0) =>
Unit = Unit0,
( current_unit(Unit, Module, _Supers, Options)
-> true
; throw_error(existence_error(unit_test, Unit), _)
).
%! count_tests(+Units0, -Units, -Count) is det.
%
% Count the number of tests to run. A forall(Generator, Test) counts
% as a single test. During the execution, the concrete tests of the
% _forall_ are considered "sub tests".
count_tests(Units0, Units, Count) :-
count_tests(Units0, Units, 0, Count).
count_tests([], T, C0, C) =>
T = [],
C = C0.
count_tests([_:[]|T0], T, C0, C) =>
count_tests(T0, T, C0, C).
count_tests([Unit:Tests|T0], T, C0, C) =>
partition(is_blocked, Tests, Blocked, Use),
maplist(assert_blocked(Unit), Blocked),
( Use == []
-> count_tests(T0, T, C0, C)
; length(Use, N),
C1 is C0+N,
T = [Unit:Use|T1],
count_tests(T0, T1, C1, C)
).
is_blocked(@(blocked(_,_),_)) => true.
is_blocked(_) => fail.
assert_blocked(Unit, @(blocked(Test, Reason), Line)) =>
assert(blocked(Unit, Test, Line, Reason)).
%! run_unit(+Unit) is det.
%
% Run a single test unit. Unit is a term Unit:Tests, where Tests is a
% list of tests to run.
run_unit(_Unit:[]) =>
true.
run_unit(Unit:Tests) =>
unit_module(Unit, Module),
unit_options(Unit, UnitOptions),
( setup(Module, unit(Unit), UnitOptions)
-> begin_unit(Unit),
call_time(run_unit_2(Unit, Tests), Time),
test_summary(Unit, Summary),
end_unit(Unit, Summary.put(time, Time)),
cleanup(Module, UnitOptions)
; job_info(end(unit(Unit, _{error:setup_failed})))
).
begin_unit(Unit) :-
job_info(begin(unit(Unit))),
job_feedback(informational, begin(Unit)).
end_unit(Unit, Summary) :-
job_info(end(unit(Unit, Summary))),
job_feedback(informational, end(Unit, Summary)).
run_unit_2(Unit, Tests) :-
forall(member(Test, Tests),
run_test(Unit, Test)).
unit_options(Unit, Options) :-
current_unit(Unit, _Module, _Supers, Options).
cleanup :-
set_flag(plunit_test, 1),
retractall(output_streams(_,_)),
retractall(test_count(_)),
retractall(passed(_, _, _, _, _)),
retractall(failed(_, _, _, _, _)),
retractall(timeout(_, _, _, _, _)),
retractall(failed_assertion(_, _, _, _, _, _, _)),
retractall(blocked(_, _, _, _)),
retractall(fixme(_, _, _, _, _)),
retractall(running(_,_,_,_,_)),
retractall(forall_failures(_,_)).
cleanup_after_test :-
( current_test_flag(cleanup, true)
-> cleanup
; true
).
%! run_tests_in_files(+Files:list) is det.
%
% Run all test-units that appear in the given Files.
run_tests_in_files(Files) :-
findall(Unit, unit_in_files(Files, Unit), Units),
( Units == []
-> true
; run_tests(Units)
).
unit_in_files(Files, Unit) :-
is_list(Files),
!,
member(F, Files),
absolute_file_name(F, Source,
[ file_type(prolog),
access(read),
file_errors(fail)
]),
unit_file(Unit, Source).
/*******************************
* HOOKING MAKE/0 *
*******************************/
%! make_run_tests(+Files)
%
% Called indirectly from make/0 after Files have been reloaded.
make_run_tests(Files) :-
current_test_flag(run, When),
( When == make
-> run_tests_in_files(Files)
; When == make(all)
-> run_tests
; true
).
/*******************************
* ASSERTION HANDLING *
*******************************/
:- if(swi).
:- dynamic prolog:assertion_failed/2.
setup_trap_assertions(Ref) :-
asserta((prolog:assertion_failed(Reason, Goal) :-
test_assertion_failed(Reason, Goal)),
Ref).
cleanup_trap_assertions(Ref) :-
erase(Ref).
test_assertion_failed(Reason, Goal) :-
thread_self(Me),
running(Unit, Test, Line, Progress, Me),
( catch(get_prolog_backtrace(10, Stack), _, fail),
assertion_location(Stack, AssertLoc)
-> true
; AssertLoc = unknown
),
report_failed_assertion(Unit:Test, Line, AssertLoc,
Progress, Reason, Goal),
assert_cyclic(failed_assertion(Unit, Test, Line, AssertLoc,
Progress, Reason, Goal)).
assertion_location(Stack, File:Line) :-
append(_, [AssertFrame,CallerFrame|_], Stack),
prolog_stack_frame_property(AssertFrame,
predicate(prolog_debug:assertion/1)),
!,
prolog_stack_frame_property(CallerFrame, location(File:Line)).
report_failed_assertion(UnitTest, Line, AssertLoc,
Progress, Reason, Goal) :-
print_message(
error,
plunit(failed_assertion(UnitTest, Line, AssertLoc,
Progress, Reason, Goal))).
:- else.
setup_trap_assertions(_).
cleanup_trap_assertions(_).