37
38:- module(plunit,
39 [ set_test_options/1, 40 begin_tests/1, 41 begin_tests/2, 42 end_tests/1, 43 run_tests/0, 44 run_tests/1, 45 run_tests/2, 46 load_test_files/1, 47 running_tests/0, 48 current_test/5, 49 current_test_unit/2, 50 test_report/1 51 ]). 52
58
59:- autoload(library(statistics), [call_time/2]). 60:- autoload(library(apply),
61 [maplist/3, include/3, maplist/2, foldl/4, partition/4]). 62:- autoload(library(lists), [member/2, append/2, flatten/2, append/3]). 63:- autoload(library(option), [ option/3, option/2, select_option/3 ]). 64:- autoload(library(ordsets), [ord_intersection/3]). 65:- autoload(library(error), [must_be/2, domain_error/2]). 66:- autoload(library(aggregate), [aggregate_all/3]). 67:- autoload(library(streams), [with_output_to/3]). 68:- autoload(library(ansi_term), [ansi_format/3]). 69:- if(exists_source(library(time))). 70:- autoload(library(time), [call_with_time_limit/2]). 71:- endif. 72
73:- public
74 unit_module/2. 75
76:- meta_predicate
77 valid_options(1, +),
78 count(0, -). 79
80 83
84swi :- catch(current_prolog_flag(dialect, swi), _, fail).
85sicstus :- catch(current_prolog_flag(dialect, sicstus), _, fail).
86
87throw_error(Error_term,Impldef) :-
88 throw(error(Error_term,context(Impldef,_))).
89
90:- set_prolog_flag(generate_debug_info, false). 91current_test_flag(optimise, Value) =>
92 current_prolog_flag(optimise, Value).
93current_test_flag(occurs_check, Value) =>
94 ( current_prolog_flag(plunit_occurs_check, Value0)
95 -> Value = Value0
96 ; current_prolog_flag(occurs_check, Value)
97 ).
98current_test_flag(Name, Value), atom(Name) =>
99 atom_concat(plunit_, Name, Flag),
100 current_prolog_flag(Flag, Value).
101current_test_flag(Name, Value), var(Name) =>
102 global_test_option(Opt, _, _Type, _Default),
103 functor(Opt, Name, 1),
104 current_test_flag(Name, Value).
105
106set_test_flag(Name, Value) :-
107 Opt =.. [Name, Value],
108 global_test_option(Opt),
109 !,
110 atom_concat(plunit_, Name, Flag),
111 set_prolog_flag(Flag, Value).
112set_test_flag(Name, _) :-
113 domain_error(test_flag, Name).
114
115current_test_flags(Flags) :-
116 findall(Flag, current_test_flag(Flag), Flags).
117
118current_test_flag(Opt) :-
119 current_test_flag(Name, Value),
120 Opt =.. [Name, Value].
121
123goal_expansion(forall(C,A),
124 \+ (C, \+ A)).
125goal_expansion(current_module(Module,File),
126 module_property(Module, file(File))).
127
128
129 132
133:- initialization init_flags. 134
135init_flags :-
136 ( global_test_option(Option, _Value, Type, Default),
137 Default \== (-),
138 Option =.. [Name,_],
139 atom_concat(plunit_, Name, Flag),
140 flag_type(Type, FlagType),
141 create_prolog_flag(Flag, Default, [type(FlagType), keep(true)]),
142 fail
143 ; true
144 ).
145
146flag_type(boolean, FlagType) => FlagType = boolean.
147flag_type(Type, FlagType), Type = oneof(Atoms), maplist(atom, Atoms) =>
148 FlagType = Type.
149flag_type(oneof(_), FlagType) => FlagType = term.
150flag_type(positive_integer, FlagType) => FlagType = integer.
151flag_type(number, FlagType) => FlagType = float.
152
153
154
202
203set_test_options(Options) :-
204 flatten([Options], List),
205 maplist(set_test_option, List).
206
207set_test_option(sto(true)) =>
208 print_message(warning, plunit(sto(true))).
209set_test_option(jobs(Jobs)) =>
210 must_be(positive_integer, Jobs),
211 set_test_option_flag(jobs(Jobs)).
212set_test_option(Option),
213 compound(Option), global_test_option(Option) =>
214 set_test_option_flag(Option).
215set_test_option(Option) =>
216 domain_error(option, Option).
217
218global_test_option(Opt) :-
219 global_test_option(Opt, Value, Type, _Default),
220 must_be(Type, Value).
221
222global_test_option(load(Load), Load, oneof([never,always,normal]), normal).
223global_test_option(output(Cond), Cond, oneof([always,on_failure]), on_failure).
224global_test_option(format(Feedback), Feedback, oneof([tty,log]), tty).
225global_test_option(silent(Silent), Silent, boolean, false).
226global_test_option(show_blocked(Blocked), Blocked, boolean, false).
227global_test_option(run(When), When, oneof([manual,make,make(all)]), make).
228global_test_option(occurs_check(Mode), Mode, oneof([false,true,error]), -).
229global_test_option(cleanup(Bool), Bool, boolean, true).
230global_test_option(jobs(Count), Count, positive_integer, 1).
231global_test_option(timeout(Number), Number, number, 3600).
232
233set_test_option_flag(Option) :-
234 Option =.. [Name, Value],
235 set_test_flag(Name, Value).
236
240
241loading_tests :-
242 current_test_flag(load, Load),
243 ( Load == always
244 -> true
245 ; Load == normal,
246 \+ current_test_flag(optimise, true)
247 ).
248
249 252
253:- thread_local
254 loading_unit/4. 255:- dynamic
256 current_unit/4, 257 test_file_for/2. 258
264
265begin_tests(Unit) :-
266 begin_tests(Unit, []).
267
268begin_tests(Unit, Options) :-
269 must_be(atom, Unit),
270 map_sto_option(Options, Options1),
271 valid_options(test_set_option, Options1),
272 make_unit_module(Unit, Name),
273 source_location(File, Line),
274 begin_tests(Unit, Name, File:Line, Options1).
275
276map_sto_option(Options0, Options) :-
277 select_option(sto(Mode), Options0, Options1),
278 !,
279 map_sto(Mode, Flag),
280 Options = [occurs_check(Flag)|Options1].
281map_sto_option(Options, Options).
282
283map_sto(rational_trees, Flag) => Flag = false.
284map_sto(finite_trees, Flag) => Flag = true.
285map_sto(Mode, _) => domain_error(sto, Mode).
286
287
288:- if(swi). 289begin_tests(Unit, Name, File:Line, Options) :-
290 loading_tests,
291 !,
292 '$set_source_module'(Context, Context),
293 ( current_unit(Unit, Name, Context, Options)
294 -> true
295 ; retractall(current_unit(Unit, Name, _, _)),
296 assert(current_unit(Unit, Name, Context, Options))
297 ),
298 '$set_source_module'(Old, Name),
299 '$declare_module'(Name, test, Context, File, Line, false),
300 discontiguous(Name:'unit test'/4),
301 '$set_predicate_attribute'(Name:'unit test'/4, trace, false),
302 discontiguous(Name:'unit body'/2),
303 asserta(loading_unit(Unit, Name, File, Old)).
304begin_tests(Unit, Name, File:_Line, _Options) :-
305 retractall(current_unit(Unit, Name, _, _)), 306 '$set_source_module'(Old, Old),
307 asserta(loading_unit(Unit, Name, File, Old)).
308
309:- else. 310
312
313user:term_expansion((:- begin_tests(Set)),
314 [ (:- begin_tests(Set)),
315 (:- discontiguous(test/2)),
316 (:- discontiguous('unit body'/2)),
317 (:- discontiguous('unit test'/4))
318 ]).
319
320begin_tests(Unit, Name, File:_Line, Options) :-
321 loading_tests,
322 !,
323 ( current_unit(Unit, Name, _, Options)
324 -> true
325 ; retractall(current_unit(Unit, Name, _, _)),
326 assert(current_unit(Unit, Name, -, Options))
327 ),
328 asserta(loading_unit(Unit, Name, File, -)).
329begin_tests(Unit, Name, File:_Line, _Options) :-
330 retractall(current_unit(Unit, Name, _, _)),
331 asserta(loading_unit(Unit, Name, File, -)).
332
333:- endif. 334
341
342end_tests(Unit) :-
343 loading_unit(StartUnit, _, _, _),
344 !,
345 ( Unit == StartUnit
346 -> once(retract(loading_unit(StartUnit, _, _, Old))),
347 '$set_source_module'(_, Old)
348 ; throw_error(context_error(plunit_close(Unit, StartUnit)), _)
349 ).
350end_tests(Unit) :-
351 throw_error(context_error(plunit_close(Unit, -)), _).
352
355
356:- if(swi). 357
358unit_module(Unit, Module) :-
359 atom_concat('plunit_', Unit, Module).
360
361make_unit_module(Unit, Module) :-
362 unit_module(Unit, Module),
363 ( current_module(Module),
364 \+ current_unit(_, Module, _, _),
365 predicate_property(Module:H, _P),
366 \+ predicate_property(Module:H, imported_from(_M))
367 -> throw_error(permission_error(create, plunit, Unit),
368 'Existing module')
369 ; true
370 ).
371
372:- else. 373
374:- dynamic
375 unit_module_store/2. 376
377unit_module(Unit, Module) :-
378 unit_module_store(Unit, Module),
379 !.
380
381make_unit_module(Unit, Module) :-
382 prolog_load_context(module, Module),
383 assert(unit_module_store(Unit, Module)).
384
385:- endif. 386
387 390
395
396expand_test(Name, Options0, Body,
397 [ 'unit test'(Name, Line, Options, Module:'unit body'(Id, Vars)),
398 ('unit body'(Id, Vars) :- !, Body)
399 ]) :-
400 source_location(_File, Line),
401 prolog_load_context(module, Module),
402 ( prolog_load_context(variable_names, Bindings)
403 -> true
404 ; Bindings = []
405 ),
406 atomic_list_concat([Name, '@line ', Line], Id),
407 term_variables(Options0, OptionVars0), sort(OptionVars0, OptionVars),
408 term_variables(Body, BodyVars0), sort(BodyVars0, BodyVars),
409 ord_intersection(OptionVars, BodyVars, VarList),
410 Vars =.. [vars|VarList],
411 ( is_list(Options0) 412 -> Options1 = Options0
413 ; Options1 = [Options0]
414 ),
415 maplist(expand_option(Bindings), Options1, Options2),
416 join_true_options(Options2, Options3),
417 map_sto_option(Options3, Options4),
418 valid_options(test_option, Options4),
419 valid_test_mode(Options4, Options).
420
421expand_option(_, Var, _) :-
422 var(Var),
423 !,
424 throw_error(instantiation_error,_).
425expand_option(Bindings, Cmp, true(Cond)) :-
426 cmp(Cmp),
427 !,
428 var_cmp(Bindings, Cmp, Cond).
429expand_option(_, error(X), throws(error(X, _))) :- !.
430expand_option(_, exception(X), throws(X)) :- !. 431expand_option(_, error(F,C), throws(error(F,C))) :- !. 432expand_option(_, true, true(true)) :- !.
433expand_option(_, O, O).
434
435cmp(_ == _).
436cmp(_ = _).
437cmp(_ =@= _).
438cmp(_ =:= _).
439
440var_cmp(Bindings, Expr, cmp(Name, Expr)) :-
441 arg(_, Expr, Var),
442 var(Var),
443 member(Name=V, Bindings),
444 V == Var,
445 !.
446var_cmp(_, Expr, Expr).
447
448join_true_options(Options0, Options) :-
449 partition(true_option, Options0, True, Rest),
450 True \== [],
451 !,
452 maplist(arg(1), True, Conds0),
453 flatten(Conds0, Conds),
454 Options = [true(Conds)|Rest].
455join_true_options(Options, Options).
456
457true_option(true(_)).
458
459valid_test_mode(Options0, Options) :-
460 include(test_mode, Options0, Tests),
461 ( Tests == []
462 -> Options = [true([true])|Options0]
463 ; Tests = [_]
464 -> Options = Options0
465 ; throw_error(plunit(incompatible_options, Tests), _)
466 ).
467
468test_mode(true(_)).
469test_mode(all(_)).
470test_mode(set(_)).
471test_mode(fail).
472test_mode(throws(_)).
473
474
476
477expand(end_of_file, _) :-
478 loading_unit(Unit, _, _, _),
479 !,
480 end_tests(Unit), 481 fail.
482expand((:-end_tests(_)), _) :-
483 !,
484 fail.
485expand(_Term, []) :-
486 \+ loading_tests.
487expand((test(Name) :- Body), Clauses) :-
488 !,
489 expand_test(Name, [], Body, Clauses).
490expand((test(Name, Options) :- Body), Clauses) :-
491 !,
492 expand_test(Name, Options, Body, Clauses).
493expand(test(Name), _) :-
494 !,
495 throw_error(existence_error(body, test(Name)), _).
496expand(test(Name, _Options), _) :-
497 !,
498 throw_error(existence_error(body, test(Name)), _).
499
500:- multifile
501 system:term_expansion/2. 502
503system:term_expansion(Term, Expanded) :-
504 ( loading_unit(_, _, File, _)
505 -> source_location(ThisFile, _),
506 ( File == ThisFile
507 -> true
508 ; source_file_property(ThisFile, included_in(File, _))
509 ),
510 expand(Term, Expanded)
511 ).
512
513
514 517
524
525valid_options(Pred, Options) :-
526 must_be(list, Options),
527 verify_options(Options, Pred).
528
529verify_options([], _).
530verify_options([H|T], Pred) :-
531 ( call(Pred, H)
532 -> verify_options(T, Pred)
533 ; throw_error(domain_error(Pred, H), _)
534 ).
535
536valid_options(Pred, Options0, Options, Rest) :-
537 must_be(list, Options0),
538 partition(Pred, Options0, Options, Rest).
539
543
544test_option(Option) :-
545 test_set_option(Option),
546 !.
547test_option(true(_)).
548test_option(fail).
549test_option(throws(_)).
550test_option(all(_)).
551test_option(set(_)).
552test_option(nondet).
553test_option(fixme(_)).
554test_option(forall(X)) :-
555 must_be(callable, X).
556test_option(timeout(Seconds)) :-
557 must_be(number, Seconds).
558
563
564test_set_option(blocked(X)) :-
565 must_be(ground, X).
566test_set_option(condition(X)) :-
567 must_be(callable, X).
568test_set_option(setup(X)) :-
569 must_be(callable, X).
570test_set_option(cleanup(X)) :-
571 must_be(callable, X).
572test_set_option(occurs_check(V)) :-
573 must_be(oneof([false,true,error]), V).
574test_set_option(concurrent(V)) :-
575 must_be(boolean, V),
576 print_message(informational, plunit(concurrent)).
577test_set_option(timeout(Seconds)) :-
578 must_be(number, Seconds).
579
580 583
584:- meta_predicate
585 reify_tmo(0, -, +),
586 reify(0, -),
587 capture_output(0,-),
588 capture_output(0,-,+),
589 got_messages(0,-). 590
592
593:- if(current_predicate(call_with_time_limit/2)). 594reify_tmo(Goal, Result, Options) :-
595 option(timeout(Time), Options),
596 Time > 0,
597 !,
598 reify(call_with_time_limit(Time, Goal), Result0),
599 ( Result0 = throw(time_limit_exceeded)
600 -> Result = throw(time_limit_exceeded(Time))
601 ; Result = Result0
602 ).
603:- endif. 604reify_tmo(Goal, Result, _Options) :-
605 reify(Goal, Result).
606
611
612reify(Goal, Result) :-
613 ( catch(Goal, E, true)
614 -> ( var(E)
615 -> Result = true
616 ; Result = throw(E)
617 )
618 ; Result = false
619 ).
620
627
628capture_output(Goal, Output) :-
629 current_test_flag(output, OutputMode),
630 capture_output(Goal, Output, [output(OutputMode)]).
631
632capture_output(Goal, Msgs-Output, Options) :-
633 option(output(How), Options, always),
634 ( How == always
635 -> call(Goal),
636 Msgs = false 637 ; with_output_to(string(Output), got_messages(Goal, Msgs),
638 [ capture([user_output, user_error]),
639 color(true)
640 ])
641 ).
642
649
650got_messages(Goal, Result) :-
651 ( current_prolog_flag(on_warning, status)
652 ; current_prolog_flag(on_error, status)
653 ), !,
654 message_counts(Errors0, Warnings0),
655 call(Goal),
656 message_counts(Errors, Warnings),
657 ( ( current_prolog_flag(on_warning, status),
658 Warnings > Warnings0
659 ; current_prolog_flag(on_error, status),
660 Errors > Errors0
661 )
662 -> Result = true
663 ; Result = false
664 ).
665got_messages(Goal, false) :-
666 call(Goal).
667
671
672:- if(current_predicate(system:thread_statistics/3)). 673message_counts(Errors, Warnings) :-
674 thread_self(Me),
675 thread_statistics(Me, errors, Errors),
676 thread_statistics(Me, warnings, Warnings).
677:- else. 678message_counts(Errors, Warnings) :-
679 statistics(errors, Errors),
680 statistics(warnings, Warnings).
681:- endif. 682
683
684 687
688:- dynamic
689 output_streams/2, 690 test_count/1, 691 passed/5, 692 failed/5, 693 timeout/5, 694 failed_assertion/7, 695 blocked/4, 696 fixme/5, 697 running/5, 698 forall_failures/2. 699
729
730run_tests :-
731 run_tests(all).
732
733run_tests(Set) :-
734 run_tests(Set, []).
735
736run_tests(all, Options) :-
737 !,
738 findall(Unit, current_test_unit(Unit,_), Units),
739 run_tests(Units, Options).
740run_tests(Set, Options) :-
741 valid_options(global_test_option, Options, Global, Rest),
742 current_test_flags(Old),
743 setup_call_cleanup(
744 set_test_options(Global),
745 ( flatten([Set], List),
746 maplist(runnable_tests, List, Units),
747 with_mutex(plunit, run_tests_sync(Units, Rest))
748 ),
749 set_test_options(Old)).
750
751run_tests_sync(Units0, Options) :-
752 cleanup,
753 count_tests(Units0, Units, Count),
754 asserta(test_count(Count)),
755 save_output_state,
756 setup_call_cleanup(
757 setup_trap_assertions(Ref),
758 call_time(setup_jobs_and_run_units(Count, Units, Summary, Options),
759 Time),
760 report_and_cleanup(Ref, Time, Options)),
761 ( option(summary(Summary), Options)
762 -> true
763 ; test_summary_passed(Summary) 764 ).
765
766setup_jobs_and_run_units(Count, Units, Summary, Options) :-
767 setup_call_cleanup(
768 setup_jobs(Count),
769 ( run_units(Units, Options),
770 test_summary(_All, Summary)
771 ),
772 cleanup_jobs).
773
778
779report_and_cleanup(Ref, Time, Options) :-
780 cleanup_trap_assertions(Ref),
781 report(Time, Options),
782 cleanup_after_test.
783
784
788
789run_units(Units, _Options) :-
790 maplist(schedule_unit, Units),
791 job_wait(_).
792
799
800:- det(runnable_tests/2). 801runnable_tests(Spec, Unit:RunnableTests) :-
802 unit_from_spec(Spec, Unit, Tests, Module, UnitOptions),
803 ( option(blocked(Reason), UnitOptions)
804 -> info(plunit(blocked(unit(Unit, Reason)))),
805 RunnableTests = []
806 ; \+ condition(Module, unit(Unit), UnitOptions)
807 -> RunnableTests = []
808 ; var(Tests)
809 -> findall(TestID,
810 runnable_test(Unit, _Test, Module, TestID),
811 RunnableTests)
812 ; flatten([Tests], TestList),
813 findall(TestID,
814 ( member(Test, TestList),
815 runnable_test(Unit,Test,Module, TestID)
816 ),
817 RunnableTests)
818 ).
819
820runnable_test(Unit, Name, Module, @(Test,Line)) :-
821 current_test(Unit, Name, Line, _Body, TestOptions),
822 ( option(blocked(Reason), TestOptions)
823 -> Test = blocked(Name, Reason)
824 ; condition(Module, test(Unit,Name,Line), TestOptions),
825 Test = Name
826 ).
827
828unit_from_spec(Unit0:Tests0, Unit, Tests, Module, Options), atom(Unit0) =>
829 Unit = Unit0,
830 Tests = Tests0,
831 ( current_unit(Unit, Module, _Supers, Options)
832 -> true
833 ; throw_error(existence_error(unit_test, Unit), _)
834 ).
835unit_from_spec(Unit0, Unit, _, Module, Options), atom(Unit0) =>
836 Unit = Unit0,
837 ( current_unit(Unit, Module, _Supers, Options)
838 -> true
839 ; throw_error(existence_error(unit_test, Unit), _)
840 ).
841
847
848count_tests(Units0, Units, Count) :-
849 count_tests(Units0, Units, 0, Count).
850
851count_tests([], T, C0, C) =>
852 T = [],
853 C = C0.
854count_tests([_:[]|T0], T, C0, C) =>
855 count_tests(T0, T, C0, C).
856count_tests([Unit:Tests|T0], T, C0, C) =>
857 partition(is_blocked, Tests, Blocked, Use),
858 maplist(assert_blocked(Unit), Blocked),
859 ( Use == []
860 -> count_tests(T0, T, C0, C)
861 ; length(Use, N),
862 C1 is C0+N,
863 T = [Unit:Use|T1],
864 count_tests(T0, T1, C1, C)
865 ).
866
867is_blocked(@(blocked(_,_),_)) => true.
868is_blocked(_) => fail.
869
870assert_blocked(Unit, @(blocked(Test, Reason), Line)) =>
871 assert(blocked(Unit, Test, Line, Reason)).
872
877
878run_unit(_Unit:[]) =>
879 true.
880run_unit(Unit:Tests) =>
881 unit_module(Unit, Module),
882 unit_options(Unit, UnitOptions),
883 ( setup(Module, unit(Unit), UnitOptions)
884 -> begin_unit(Unit),
885 call_time(run_unit_2(Unit, Tests), Time),
886 test_summary(Unit, Summary),
887 end_unit(Unit, Summary.put(time, Time)),
888 cleanup(Module, UnitOptions)
889 ; job_info(end(unit(Unit, _{error:setup_failed})))
890 ).
891
892begin_unit(Unit) :-
893 job_info(begin(unit(Unit))),
894 job_feedback(informational, begin(Unit)).
895
896end_unit(Unit, Summary) :-
897 job_info(end(unit(Unit, Summary))),
898 job_feedback(informational, end(Unit, Summary)).
899
900run_unit_2(Unit, Tests) :-
901 forall(member(Test, Tests),
902 run_test(Unit, Test)).
903
904
905unit_options(Unit, Options) :-
906 current_unit(Unit, _Module, _Supers, Options).
907
908
909cleanup :-
910 set_flag(plunit_test, 1),
911 retractall(output_streams(_,_)),
912 retractall(test_count(_)),
913 retractall(passed(_, _, _, _, _)),
914 retractall(failed(_, _, _, _, _)),
915 retractall(timeout(_, _, _, _, _)),
916 retractall(failed_assertion(_, _, _, _, _, _, _)),
917 retractall(blocked(_, _, _, _)),
918 retractall(fixme(_, _, _, _, _)),
919 retractall(running(_,_,_,_,_)),
920 retractall(forall_failures(_,_)).
921
922cleanup_after_test :-
923 ( current_test_flag(cleanup, true)
924 -> cleanup
925 ; true
926 ).
927
928
932
933run_tests_in_files(Files) :-
934 findall(Unit, unit_in_files(Files, Unit), Units),
935 ( Units == []
936 -> true
937 ; run_tests(Units)
938 ).
939
940unit_in_files(Files, Unit) :-
941 is_list(Files),
942 !,
943 member(F, Files),
944 absolute_file_name(F, Source,
945 [ file_type(prolog),
946 access(read),
947 file_errors(fail)
948 ]),
949 unit_file(Unit, Source).
950
951
952 955
959
960make_run_tests(Files) :-
961 current_test_flag(run, When),
962 ( When == make
963 -> run_tests_in_files(Files)
964 ; When == make(all)
965 -> run_tests
966 ; true
967 ).
968
969 972
973:- if(swi). 974
975:- dynamic prolog:assertion_failed/2. 976
977setup_trap_assertions(Ref) :-
978 asserta((prolog:assertion_failed(Reason, Goal) :-
979 test_assertion_failed(Reason, Goal)),
980 Ref).
981
982cleanup_trap_assertions(Ref) :-
983 erase(Ref).
984
985test_assertion_failed(Reason, Goal) :-
986 thread_self(Me),
987 running(Unit, Test, Line, Progress, Me),
988 ( catch(get_prolog_backtrace(10, Stack), _, fail),
989 assertion_location(Stack, AssertLoc)
990 -> true
991 ; AssertLoc = unknown
992 ),
993 report_failed_assertion(Unit:Test, Line, AssertLoc,
994 Progress, Reason, Goal),
995 assert_cyclic(failed_assertion(Unit, Test, Line, AssertLoc,
996 Progress, Reason, Goal)).
997
998assertion_location(Stack, File:Line) :-
999 append(_, [AssertFrame,CallerFrame|_], Stack),
1000 prolog_stack_frame_property(AssertFrame,
1001 predicate(prolog_debug:assertion/1)),
1002 !,
1003 prolog_stack_frame_property(CallerFrame, location(File:Line)).
1004
1005report_failed_assertion(UnitTest, Line, AssertLoc,
1006 Progress, Reason, Goal) :-
1007 print_message(
1008 error,
1009 plunit(failed_assertion(UnitTest, Line, AssertLoc,
1010 Progress, Reason, Goal))).
1011
1012:- else. 1013
1014setup_trap_assertions(_).
1015cleanup_trap_assertions(_).
1016
1017:- endif. 1018
1019
1020 1023
1027
1028run_test(Unit, @(Test,Line)) :-
1029 unit_module(Unit, Module),
1030 Module:'unit test'(Test, Line, TestOptions, Body),
1031 unit_options(Unit, UnitOptions),
1032 run_test(Unit, Test, Line, UnitOptions, TestOptions, Body).
1033
1037
1038run_test(Unit, Name, Line, UnitOptions, Options, Body) :-
1039 option(forall(Generator), Options),
1040 !,
1041 unit_module(Unit, Module),
1042 start_test(Unit, @(Name,Line), Nth),
1043 State = state(0),
1044 call_time(forall(Module:Generator, 1045 ( incr_forall(State, I),
1046 run_test_once6(Unit, Name,
1047 forall(Generator, Nth-I), Line,
1048 UnitOptions, Options, Body)
1049 )),
1050 Time),
1051 arg(1, State, Generated),
1052 progress(Unit:Name, Nth, forall(end, Nth, Generated), Time).
1053run_test(Unit, Name, Line, UnitOptions, Options, Body) :-
1054 start_test(Unit, @(Name,Line), Nth),
1055 run_test_once6(Unit, Name, Nth, Line, UnitOptions, Options, Body).
1056
1057start_test(_Unit, _TestID, Nth) :-
1058 flag(plunit_test, Nth, Nth+1).
1059
1060incr_forall(State, I) :-
1061 arg(1, State, I0),
1062 I is I0+1,
1063 nb_setarg(1, State, I).
1064
1069
1070run_test_once6(Unit, Name, Progress, Line, UnitOptions, Options, Body) :-
1071 current_test_flag(timeout, DefTimeOut),
1072 current_test_flag(occurs_check, DefOccurs),
1073 inherit_option(timeout, Options, [UnitOptions], DefTimeOut, Options1),
1074 inherit_option(occurs_check, Options1, [UnitOptions], DefOccurs, Options2),
1075 run_test_once(Unit, Name, Progress, Line, Options2, Body).
1076
1077inherit_option(Name, Options0, Chain, Default, Options) :-
1078 Term =.. [Name,_Value],
1079 ( option(Term, Options0)
1080 -> Options = Options0
1081 ; member(Opts, Chain),
1082 option(Term, Opts)
1083 -> Options = [Term|Options0]
1084 ; Default == (-)
1085 -> Options = Options0
1086 ; Opt =.. [Name,Default],
1087 Options = [Opt|Options0]
1088 ).
1089
1094
1095run_test_once(Unit, Name, Progress, Line, Options, Body) :-
1096 option(occurs_check(Occurs), Options),
1097 !,
1098 begin_test(Unit, Name, Line, Progress),
1099 setup_call_cleanup(
1100 push_prolog_flag(occurs_check, Occurs),
1101 capture_output(run_test_6(Unit, Name, Line, Options, Body, Result),
1102 Output),
1103 pop_prolog_flag(occurs_check)),
1104 end_test(Unit, Name, Line, Progress),
1105 report_result(Result, Progress, Output, Options).
1106run_test_once(Unit, Name, Progress, Line, Options, Body) :-
1107 begin_test(Unit, Name, Line, Progress),
1108 capture_output(run_test_6(Unit, Name, Line, Options, Body, Result),
1109 Output),
1110 end_test(Unit, Name, Line, Progress),
1111 report_result(Result, Progress, Output, Options).
1112
1114
1115:- det(report_result/4). 1116report_result(failure(Unit, Name, Line, How, Time),
1117 Progress, Output, Options) =>
1118 failure(Unit, Name, Progress, Line, How, Time, Output, Options).
1119report_result(success(Unit, Name, Line, Determinism, Time),
1120 Progress, Output, Options) =>
1121 success(Unit, Name, Progress, Line, Determinism, Time, Output, Options).
1122report_result(setup_failed(Unit, Name, Line, Time, Output, Result),
1123 Progress, _Output, Options) =>
1124 failure(Unit, Name, Progress, Line,
1125 setup_failed(Result), Time, Output, Options).
1126
1146
1147run_test_6(Unit, Name, Line, Options, Body, Result) :-
1148 option(setup(Setup), Options),
1149 !,
1150 unit_module(Unit, Module),
1151 capture_output(call_time(reify(call_ex(Module, Setup), SetupResult),
1152 Time),
1153 Output),
1154 ( SetupResult == true
1155 -> run_test_7(Unit, Name, Line, Options, Body, Result),
1156 cleanup(Module, Options)
1157 ; Result = setup_failed(Unit, Name, Line, Time, Output, SetupResult)
1158 ).
1159run_test_6(Unit, Name, Line, Options, Body, Result) :-
1160 unit_module(Unit, Module),
1161 run_test_7(Unit, Name, Line, Options, Body, Result),
1162 cleanup(Module, Options).
1163
1170
1171run_test_7(Unit, Name, Line, Options, Body, Result) :-
1172 option(true(Cmp), Options), 1173 !,
1174 unit_module(Unit, Module),
1175 call_time(reify_tmo(call_det(Module:Body, Det), Result0, Options), Time),
1176 ( Result0 == true
1177 -> cmp_true(Cmp, Module, CmpResult),
1178 ( CmpResult == []
1179 -> Result = success(Unit, Name, Line, Det, Time)
1180 ; Result = failure(Unit, Name, Line, CmpResult, Time)
1181 )
1182 ; Result0 == false
1183 -> Result = failure(Unit, Name, Line, failed, Time)
1184 ; Result0 = throw(E2)
1185 -> Result = failure(Unit, Name, Line, throw(E2), Time)
1186 ).
1187run_test_7(Unit, Name, Line, Options, Body, Result) :-
1188 option(fail, Options), 1189 !,
1190 unit_module(Unit, Module),
1191 call_time(reify_tmo(Module:Body, Result0, Options), Time),
1192 ( Result0 == true
1193 -> Result = failure(Unit, Name, Line, succeeded, Time)
1194 ; Result0 == false
1195 -> Result = success(Unit, Name, Line, true, Time)
1196 ; Result0 = throw(E)
1197 -> Result = failure(Unit, Name, Line, throw(E), Time)
1198 ).
1199run_test_7(Unit, Name, Line, Options, Body, Result) :-
1200 option(throws(Expect), Options), 1201 !,
1202 unit_module(Unit, Module),
1203 call_time(reify_tmo(Module:Body, Result0, Options), Time),
1204 ( Result0 == true
1205 -> Result = failure(Unit, Name, Line, no_exception, Time)
1206 ; Result0 == false
1207 -> Result = failure(Unit, Name, Line, failed, Time)
1208 ; Result0 = throw(E)
1209 -> ( match_error(Expect, E)
1210 -> Result = success(Unit, Name, Line, true, Time)
1211 ; Result = failure(Unit, Name, Line, wrong_error(Expect, E), Time)
1212 )
1213 ).
1214run_test_7(Unit, Name, Line, Options, Body, Result) :-
1215 option(all(Answer), Options), 1216 !,
1217 nondet_test(all(Answer), Unit, Name, Line, Options, Body, Result).
1218run_test_7(Unit, Name, Line, Options, Body, Result) :-
1219 option(set(Answer), Options), 1220 !,
1221 nondet_test(set(Answer), Unit, Name, Line, Options, Body, Result).
1222
1226
1227nondet_test(Expected, Unit, Name, Line, Options, Body, Result) :-
1228 unit_module(Unit, Module),
1229 result_vars(Expected, Vars),
1230 ( call_time(reify_tmo(findall(Vars, Module:Body, Bindings),
1231 Result0, Options), Time)
1232 -> ( Result0 == true
1233 -> ( nondet_compare(Expected, Bindings, Unit, Name, Line)
1234 -> Result = success(Unit, Name, Line, true, Time)
1235 ; Result = failure(Unit, Name, Line,
1236 [wrong_answer(Expected, Bindings)], Time)
1237 )
1238 ; Result0 = throw(E)
1239 -> Result = failure(Unit, Name, Line, throw(E), Time)
1240 )
1241 ).
1242
1243cmp_true([], _, L) =>
1244 L = [].
1245cmp_true([Cmp|T], Module, L) =>
1246 E = error(Formal,_),
1247 cmp_goal(Cmp, Goal),
1248 ( catch(Module:Goal, E, true)
1249 -> ( var(Formal)
1250 -> cmp_true(T, Module, L)
1251 ; L = [cmp_error(Cmp,E)|L1],
1252 cmp_true(T, Module, L1)
1253 )
1254 ; L = [wrong_answer(Cmp)|L1],
1255 cmp_true(T, Module, L1)
1256 ).
1257
1258cmp_goal(cmp(_Var, Expr), Goal) => Goal = Expr.
1259cmp_goal(Expr, Goal) => Goal = Expr.
1260
1261
1266
1267result_vars(Expected, Vars) :-
1268 arg(1, Expected, CmpOp),
1269 arg(1, CmpOp, Vars).
1270
1278
1279nondet_compare(all(Cmp), Bindings, _Unit, _Name, _Line) :-
1280 cmp(Cmp, _Vars, Op, Values),
1281 cmp_list(Values, Bindings, Op).
1282nondet_compare(set(Cmp), Bindings0, _Unit, _Name, _Line) :-
1283 cmp(Cmp, _Vars, Op, Values0),
1284 sort(Bindings0, Bindings),
1285 sort(Values0, Values),
1286 cmp_list(Values, Bindings, Op).
1287
1288cmp_list([], [], _Op).
1289cmp_list([E0|ET], [V0|VT], Op) :-
1290 call(Op, E0, V0),
1291 cmp_list(ET, VT, Op).
1292
1294
1295cmp(Var == Value, Var, ==, Value).
1296cmp(Var =:= Value, Var, =:=, Value).
1297cmp(Var = Value, Var, =, Value).
1298:- if(swi). 1299cmp(Var =@= Value, Var, =@=, Value).
1300:- else. 1301:- if(sicstus). 1302cmp(Var =@= Value, Var, variant, Value). 1303:- endif. 1304:- endif. 1305
1306
1311
1312:- if((swi;sicstus)). 1313call_det(Goal, Det) :-
1314 call_cleanup(Goal,Det0=true),
1315 ( var(Det0) -> Det = false ; Det = true ).
1316:- else. 1317call_det(Goal, true) :-
1318 call(Goal).
1319:- endif. 1320
1325
1326match_error(Expect, Rec) :-
1327 subsumes_term(Expect, Rec).
1328
1339
1340setup(Module, Context, Options) :-
1341 option(setup(Setup), Options),
1342 !,
1343 capture_output(reify(call_ex(Module, Setup), Result), Output),
1344 ( Result == true
1345 -> true
1346 ; print_message(error,
1347 plunit(error(setup, Context, Output, Result))),
1348 fail
1349 ).
1350setup(_,_,_).
1351
1355
1356condition(Module, Context, Options) :-
1357 option(condition(Cond), Options),
1358 !,
1359 capture_output(reify(call_ex(Module, Cond), Result), Output),
1360 ( Result == true
1361 -> true
1362 ; Result == false
1363 -> fail
1364 ; print_message(error,
1365 plunit(error(condition, Context, Output, Result))),
1366 fail
1367 ).
1368condition(_, _, _).
1369
1370
1374
1375call_ex(Module, Goal) :-
1376 Module:(expand_goal(Goal, GoalEx),
1377 GoalEx).
1378
1383
1384cleanup(Module, Options) :-
1385 option(cleanup(Cleanup), Options, true),
1386 ( catch(call_ex(Module, Cleanup), E, true)
1387 -> ( var(E)
1388 -> true
1389 ; print_message(warning, E)
1390 )
1391 ; print_message(warning, goal_failed(Cleanup, '(cleanup handler)'))
1392 ).
1393
1394success(Unit, Name, Progress, Line, Det, Time, _Output, Options) :-
1395 option(fixme(Reason), Options),
1396 !,
1397 ( ( Det == true
1398 ; memberchk(nondet, Options)
1399 )
1400 -> progress(Unit:Name, Progress, fixme(passed), Time),
1401 Ok = passed
1402 ; progress(Unit:Name, Progress, fixme(nondet), Time),
1403 Ok = nondet
1404 ),
1405 flush_output(user_error),
1406 assert(fixme(Unit, Name, Line, Reason, Ok)).
1407success(Unit, Name, Progress, Line, _, Time, Output, Options) :-
1408 failed_assertion(Unit, Name, Line, _,Progress,_,_),
1409 !,
1410 failure(Unit, Name, Progress, Line, assertion, Time, Output, Options).
1411success(Unit, Name, Progress, Line, _, Time, Output, Options) :-
1412 Output = true-_,
1413 !,
1414 failure(Unit, Name, Progress, Line, message, Time, Output, Options).
1415success(Unit, Name, Progress, Line, Det, Time, _Output, Options) :-
1416 assert(passed(Unit, Name, Line, Det, Time)),
1417 ( ( Det == true
1418 ; memberchk(nondet, Options)
1419 )
1420 -> progress(Unit:Name, Progress, passed, Time)
1421 ; unit_file(Unit, File),
1422 print_message(warning, plunit(nondet(File:Line, Unit:Name, Progress)))
1423 ).
1424
1429
1430failure(Unit, Name, Progress, Line, _, Time, _Output, Options),
1431 memberchk(fixme(Reason), Options) =>
1432 assert(fixme(Unit, Name, Line, Reason, failed)),
1433 progress(Unit:Name, Progress, fixme(failed), Time).
1434failure(Unit, Name, Progress, Line, time_limit_exceeded(Limit), Time,
1435 Output, Options) =>
1436 assert_cyclic(timeout(Unit, Name, Line, Limit, Time)),
1437 progress(Unit:Name, Progress, timeout(Limit), Time),
1438 report_failure(Unit, Name, Progress, Line, timeout(Limit), Time, Output, Options).
1439failure(Unit, Name, Progress, Line, E, Time, Output, Options) =>
1440 assert_cyclic(failed(Unit, Name, Line, E, Time)),
1441 progress(Unit:Name, Progress, failed, Time),
1442 report_failure(Unit, Name, Progress, Line, E, Time, Output, Options).
1443
1451
1452:- if(swi). 1453assert_cyclic(Term) :-
1454 acyclic_term(Term),
1455 !,
1456 assert(Term).
1457assert_cyclic(Term) :-
1458 Term =.. [Functor|Args],
1459 recorda(cyclic, Args, Id),
1460 functor(Term, _, Arity),
1461 length(NewArgs, Arity),
1462 Head =.. [Functor|NewArgs],
1463 assert((Head :- recorded(_, Var, Id), Var = NewArgs)).
1464:- else. 1465:- if(sicstus). 1466:- endif. 1467assert_cyclic(Term) :-
1468 assert(Term).
1469:- endif. 1470
1471
1472 1475
1476:- if(current_predicate(system:thread_statistics/3)). 1477
1478:- dynamic
1479 job_data/2, 1480 scheduled_unit/1. 1481
1482schedule_unit(_:[]) :-
1483 !.
1484schedule_unit(UnitAndTests) :-
1485 UnitAndTests = Unit:_Tests,
1486 job_data(Queue, _),
1487 !,
1488 assertz(scheduled_unit(Unit)),
1489 thread_send_message(Queue, unit(UnitAndTests)).
1490schedule_unit(Unit) :-
1491 run_unit(Unit).
1492
1496
1497setup_jobs(Count) :-
1498 ( current_test_flag(jobs, Jobs0),
1499 integer(Jobs0)
1500 -> true
1501 ; current_prolog_flag(cpu_count, Jobs0)
1502 ),
1503 Jobs is min(Count, Jobs0),
1504 Jobs > 1,
1505 !,
1506 message_queue_create(Q, [alias(plunit_jobs)]),
1507 length(TIDs, Jobs),
1508 foldl(create_plunit_job(Q), TIDs, 1, _),
1509 asserta(job_data(Q, TIDs)),
1510 job_feedback(informational, jobs(Jobs)).
1511setup_jobs(_) :-
1512 job_feedback(informational, jobs(1)).
1513
1514create_plunit_job(Q, TID, N, N1) :-
1515 N1 is N + 1,
1516 atom_concat(plunit_job_, N, Alias),
1517 thread_create(plunit_job(Q), TID, [alias(Alias)]).
1518
1519plunit_job(Queue) :-
1520 repeat,
1521 ( catch(thread_get_message(Queue, Job,
1522 [ timeout(10)
1523 ]),
1524 error(_,_), fail)
1525 -> job(Job),
1526 fail
1527 ; !
1528 ).
1529
1530job(unit(Unit:Tests)) =>
1531 run_unit(Unit:Tests).
1532job(test(Unit, Test)) =>
1533 run_test(Unit, Test).
1534
1535cleanup_jobs :-
1536 retract(job_data(Queue, TIDSs)),
1537 !,
1538 message_queue_destroy(Queue),
1539 maplist(thread_join, TIDSs).
1540cleanup_jobs.
1541
1545
1546job_wait(Unit) :-
1547 thread_wait(\+ scheduled_unit(Unit),
1548 [ wait_preds([scheduled_unit/1]),
1549 timeout(1)
1550 ]),
1551 !.
1552job_wait(Unit) :-
1553 job_data(_Queue, TIDs),
1554 member(TID, TIDs),
1555 thread_property(TID, status(running)),
1556 !,
1557 job_wait(Unit).
1558job_wait(_).
1559
1560
1561job_info(begin(unit(Unit))) =>
1562 print_message(silent, plunit(begin(Unit))).
1563job_info(end(unit(Unit, Summary))) =>
1564 retractall(scheduled_unit(Unit)),
1565 print_message(silent, plunit(end(Unit, Summary))).
1566
1567:- else. 1568
1569schedule_unit(Unit) :-
1570 run_unit(Unit).
1571
1572setup_jobs(_) :-
1573 print_message(silent, plunit(jobs(1))).
1574cleanup_jobs.
1575job_wait(_).
1576job_info(_).
1577
1578:- endif. 1579
1580
1581
1582 1585
1596
1597begin_test(Unit, Test, Line, Progress) :-
1598 thread_self(Me),
1599 assert(running(Unit, Test, Line, Progress, Me)),
1600 unit_file(Unit, File),
1601 test_count(Total),
1602 job_feedback(information, begin(Unit:Test, File:Line, Progress/Total)).
1603
1604end_test(Unit, Test, Line, Progress) :-
1605 thread_self(Me),
1606 retractall(running(_,_,_,_,Me)),
1607 unit_file(Unit, File),
1608 test_count(Total),
1609 job_feedback(information, end(Unit:Test, File:Line, Progress/Total)).
1610
1614
1615running_tests :-
1616 running_tests(Running),
1617 print_message(informational, plunit(running(Running))).
1618
1619running_tests(Running) :-
1620 test_count(Total),
1621 findall(running(Unit:Test, File:Line, Progress/Total, Thread),
1622 ( running(Unit, Test, Line, Progress, Thread),
1623 unit_file(Unit, File)
1624 ), Running).
1625
1626
1630
1631current_test(Unit, Test, Line, Body, Options) :-
1632 current_unit(Unit, Module, _Supers, _UnitOptions),
1633 Module:'unit test'(Test, Line, Options, Body).
1634
1638
1639current_test_unit(Unit, UnitOptions) :-
1640 current_unit(Unit, _Module, _Supers, UnitOptions).
1641
1642
1643count(Goal, Count) :-
1644 aggregate_all(count, Goal, Count).
1645
1650
1651test_summary(Unit, Summary) :-
1652 count(failed(Unit, _0Test, _0Line, _Reason, _0Time), Failed),
1653 count(timeout(Unit, _0Test, _0Line, _Limit, _0Time), Timeout),
1654 count(passed(Unit, _0Test, _0Line, _Det, _0Time), Passed),
1655 count(blocked(Unit, _0Test, _0Line, _0Reason), Blocked),
1656 count(fixme(Unit, _0Test, _0Line, _0Reason, _0How), Fixme),
1657 test_count(Total),
1658 Summary = plunit{total:Total,
1659 passed:Passed,
1660 failed:Failed,
1661 timeout:Timeout,
1662 blocked:Blocked,
1663 fixme:Fixme}.
1664
1665test_summary_passed(Summary) :-
1666 _{failed: 0} :< Summary.
1667
1671
1672report(Time, _Options) :-
1673 test_summary(_, Summary),
1674 print_message(silent, plunit(Summary)),
1675 _{ passed:Passed,
1676 failed:Failed,
1677 timeout:Timeout,
1678 blocked:Blocked,
1679 fixme:Fixme
1680 } :< Summary,
1681 ( Passed+Failed+Timeout+Blocked+Fixme =:= 0
1682 -> info(plunit(no_tests))
1683 ; Failed+Timeout =:= 0
1684 -> report_blocked(Blocked),
1685 report_fixme,
1686 test_count(Total),
1687 info(plunit(all_passed(Total, Passed, Time)))
1688 ; report_blocked(Blocked),
1689 report_fixme,
1690 report_failed(Failed),
1691 report_timeout(Timeout),
1692 info(plunit(passed(Passed))),
1693 info(plunit(total_time(Time)))
1694 ).
1695
1696report_blocked(0) =>
1697 true.
1698report_blocked(Blocked) =>
1699 findall(blocked(Unit:Name, File:Line, Reason),
1700 ( blocked(Unit, Name, Line, Reason),
1701 unit_file(Unit, File)
1702 ),
1703 BlockedTests),
1704 info(plunit(blocked(Blocked, BlockedTests))).
1705
1706report_failed(Failed) :-
1707 print_message(error, plunit(failed(Failed))).
1708
1709report_timeout(Count) :-
1710 print_message(warning, plunit(timeout(Count))).
1711
1712report_fixme :-
1713 report_fixme(_,_,_).
1714
1715report_fixme(TuplesF, TuplesP, TuplesN) :-
1716 fixme(failed, TuplesF, Failed),
1717 fixme(passed, TuplesP, Passed),
1718 fixme(nondet, TuplesN, Nondet),
1719 print_message(informational, plunit(fixme(Failed, Passed, Nondet))).
1720
1721
1722fixme(How, Tuples, Count) :-
1723 findall(fixme(Unit, Name, Line, Reason, How),
1724 fixme(Unit, Name, Line, Reason, How), Tuples),
1725 length(Tuples, Count).
1726
1727report_failure(Unit, Name, Progress, Line, Error,
1728 Time, Output, _Options) =>
1729 test_count(Total),
1730 job_feedback(error, failed(Unit:Name, Progress/Total, Line,
1731 Error, Time, Output)).
1732
1733
1738
1739test_report(fixme) :-
1740 !,
1741 report_fixme(TuplesF, TuplesP, TuplesN),
1742 append([TuplesF, TuplesP, TuplesN], Tuples),
1743 print_message(informational, plunit(fixme(Tuples))).
1744test_report(What) :-
1745 throw_error(domain_error(report_class, What), _).
1746
1747
1748 1751
1756
1757unit_file(Unit, File), nonvar(Unit) =>
1758 unit_file_(Unit, File),
1759 !.
1760unit_file(Unit, File) =>
1761 unit_file_(Unit, File).
1762
1763unit_file_(Unit, File) :-
1764 current_unit(Unit, Module, _Context, _Options),
1765 module_property(Module, file(File)).
1766unit_file_(Unit, PlFile) :-
1767 test_file_for(TestFile, PlFile),
1768 module_property(Module, file(TestFile)),
1769 current_unit(Unit, Module, _Context, _Options).
1770
1771
1772 1775
1780
1781load_test_files(_Options) :-
1782 State = state(0,0),
1783 ( source_file(File),
1784 file_name_extension(Base, Old, File),
1785 Old \== plt,
1786 file_name_extension(Base, plt, TestFile),
1787 exists_file(TestFile),
1788 inc_arg(1, State),
1789 ( test_file_for(TestFile, File)
1790 -> true
1791 ; load_files(TestFile,
1792 [ if(changed),
1793 imports([])
1794 ]),
1795 inc_arg(2, State),
1796 asserta(test_file_for(TestFile, File))
1797 ),
1798 fail
1799 ; State = state(Total, Loaded),
1800 print_message(informational, plunit(test_files(Total, Loaded)))
1801 ).
1802
1803inc_arg(Arg, State) :-
1804 arg(Arg, State, N0),
1805 N is N0+1,
1806 nb_setarg(Arg, State, N).
1807
1808
1809 1812
1817
1818info(Term) :-
1819 message_level(Level),
1820 print_message(Level, Term).
1821
1836
1837progress(UnitTest, _Progress, forall(end, Nth, FTotal), Time) =>
1838 ( retract(forall_failures(Nth, FFailed))
1839 -> true
1840 ; FFailed = 0
1841 ),
1842 test_count(Total),
1843 job_feedback(information, progress(UnitTest, forall(FTotal,FFailed), Nth/Total, Time)).
1844progress(UnitTest, Progress, Result, Time), Progress = forall(_Gen, Nth-_I) =>
1845 with_mutex(plunit_forall_counter,
1846 update_forall_failures(Nth, Result)),
1847 test_count(Total),
1848 job_feedback(information, progress(UnitTest, Result, Progress/Total, Time)).
1849progress(UnitTest, Progress, Result, Time) =>
1850 test_count(Total),
1851 job_feedback(information, progress(UnitTest, Result, Progress/Total, Time)).
1852
1853update_forall_failures(_Nth, passed) =>
1854 true.
1855update_forall_failures(Nth, _) =>
1856 ( retract(forall_failures(Nth, Failed0))
1857 -> true
1858 ; Failed0 = 0
1859 ),
1860 Failed is Failed0+1,
1861 asserta(forall_failures(Nth, Failed)).
1862
1863message_level(Level) :-
1864 ( current_test_flag(silent, true)
1865 -> Level = silent
1866 ; Level = informational
1867 ).
1868
1869locationprefix(File:Line) -->
1870 !,
1871 [ url(File:Line), ':'-[], nl, ' ' ].
1872locationprefix(test(Unit,_Test,Line)) -->
1873 !,
1874 { unit_file(Unit, File) },
1875 locationprefix(File:Line).
1876locationprefix(unit(Unit)) -->
1877 !,
1878 [ 'PL-Unit: unit ~w: '-[Unit] ].
1879locationprefix(FileLine) -->
1880 { throw_error(type_error(locationprefix,FileLine), _) }.
1881
1882:- discontiguous
1883 message//1. 1884:- '$hide'(message//1). 1885
1886message(error(context_error(plunit_close(Name, -)), _)) -->
1887 [ 'PL-Unit: cannot close unit ~w: no open unit'-[Name] ].
1888message(error(context_error(plunit_close(Name, Start)), _)) -->
1889 [ 'PL-Unit: cannot close unit ~w: current unit is ~w'-[Name, Start] ].
1890message(plunit(nondet(Pos, Test, Progress))) -->
1891 locationprefix(Pos),
1892 test_name(Test, Progress),
1893 [ ': Test succeeded with choicepoint'-[] ].
1894message(error(plunit(incompatible_options, Tests), _)) -->
1895 [ 'PL-Unit: incompatible test-options: ~p'-[Tests] ].
1896message(plunit(sto(true))) -->
1897 [ 'Option sto(true) is ignored. See `occurs_check` option.'-[] ].
1898message(plunit(test_files(Total, Loaded))) -->
1899 [ 'Found ~D .plt test files, loaded ~D'-[Total, Loaded] ].
1900
1901 1902message(plunit(jobs(1))) -->
1903 !.
1904message(plunit(jobs(N))) -->
1905 [ 'Testing with ~D parallel jobs'-[N] ].
1906message(plunit(begin(_Unit))) -->
1907 { tty_feedback },
1908 !.
1909message(plunit(begin(Unit))) -->
1910 [ 'Start unit: ~w~n'-[Unit], flush ].
1911message(plunit(end(_Unit, _Summary))) -->
1912 { tty_feedback },
1913 !.
1914message(plunit(end(Unit, Summary))) -->
1915 ( {test_summary_passed(Summary)}
1916 -> [ 'End unit ~w: passed (~3f sec CPU)'-[Unit, Summary.time.cpu] ]
1917 ; [ ansi(error, 'End unit ~w: **FAILED (~3f sec CPU)', [Unit, Summary.time.cpu]) ]
1918 ).
1919message(plunit(blocked(unit(Unit, Reason)))) -->
1920 [ 'PL-Unit: ~w blocked: ~w'-[Unit, Reason] ].
1921message(plunit(running([]))) -->
1922 !,
1923 [ 'PL-Unit: no tests running' ].
1924message(plunit(running([One]))) -->
1925 !,
1926 [ 'PL-Unit: running ' ],
1927 running(One).
1928message(plunit(running(More))) -->
1929 !,
1930 [ 'PL-Unit: running tests:', nl ],
1931 running(More).
1932message(plunit(fixme([]))) --> !.
1933message(plunit(fixme(Tuples))) -->
1934 !,
1935 fixme_message(Tuples).
1936message(plunit(total_time(Time))) -->
1937 [ 'Test run completed'-[] ],
1938 test_time(Time).
1939
1940 1941message(plunit(blocked(1, Tests))) -->
1942 !,
1943 [ 'one test is blocked'-[] ],
1944 blocked_tests(Tests).
1945message(plunit(blocked(N, Tests))) -->
1946 [ '~D tests are blocked'-[N] ],
1947 blocked_tests(Tests).
1948
1949blocked_tests(Tests) -->
1950 { current_test_flag(show_blocked, true) },
1951 !,
1952 [':'-[]],
1953 list_blocked(Tests).
1954blocked_tests(_) -->
1955 [ ' (use run_tests/2 with ', ansi(code, 'show_blocked(true)', []),
1956 ' for details)'-[]
1957 ].
1958
1959list_blocked([]) --> !.
1960list_blocked([blocked(Unit:Test, Pos, Reason)|T]) -->
1961 [nl],
1962 locationprefix(Pos),
1963 test_name(Unit:Test, -),
1964 [ ': ~w'-[Reason] ],
1965 list_blocked(T).
1966
1967 1968message(plunit(no_tests)) -->
1969 !,
1970 [ 'No tests to run' ].
1971message(plunit(all_passed(1, 1, Time))) -->
1972 !,
1973 [ 'test passed' ],
1974 test_time(Time).
1975message(plunit(all_passed(Total, Total, Time))) -->
1976 !,
1977 [ 'All ~D tests passed'-[Total] ],
1978 test_time(Time).
1979message(plunit(all_passed(Total, Count, Time))) -->
1980 !,
1981 { SubTests is Count-Total },
1982 [ 'All ~D (+~D sub-tests) tests passed'- [Total, SubTests] ],
1983 test_time(Time).
1984
1985test_time(Time) -->
1986 { var(Time) }, !.
1987test_time(Time) -->
1988 [ ' in ~3f seconds (~3f cpu)'-[Time.wall, Time.cpu] ].
1989
1990message(plunit(passed(Count))) -->
1991 !,
1992 [ '~D tests passed'-[Count] ].
1993message(plunit(failed(0))) -->
1994 !,
1995 [].
1996message(plunit(failed(1))) -->
1997 !,
1998 [ '1 test failed'-[] ].
1999message(plunit(failed(N))) -->
2000 [ '~D tests failed'-[N] ].
2001message(plunit(timeout(0))) -->
2002 !,
2003 [].
2004message(plunit(timeout(N))) -->
2005 [ '~D tests timed out'-[N] ].
2006message(plunit(fixme(0,0,0))) -->
2007 [].
2008message(plunit(fixme(Failed,0,0))) -->
2009 !,
2010 [ 'all ~D tests flagged FIXME failed'-[Failed] ].
2011message(plunit(fixme(Failed,Passed,0))) -->
2012 [ 'FIXME: ~D failed; ~D passed'-[Failed, Passed] ].
2013message(plunit(fixme(Failed,Passed,Nondet))) -->
2014 { TotalPassed is Passed+Nondet },
2015 [ 'FIXME: ~D failed; ~D passed; (~D nondet)'-
2016 [Failed, TotalPassed, Nondet] ].
2017
2018message(plunit(begin(Unit:Test, _Location, Progress))) -->
2019 { tty_columns(SummaryWidth, _Margin),
2020 test_name_summary(Unit:Test, SummaryWidth, NameS),
2021 progress_string(Progress, ProgressS)
2022 },
2023 ( { tty_feedback,
2024 tty_clear_to_eol(CE)
2025 }
2026 -> [ at_same_line, '\r[~w] ~w ..~w'-[ProgressS, NameS,
2027 CE], flush ]
2028 ; { jobs(_) }
2029 -> [ '[~w] ~w ..'-[ProgressS, NameS] ]
2030 ; [ '[~w] ~w ..'-[ProgressS, NameS], flush ]
2031 ).
2032message(plunit(end(_UnitTest, _Location, _Progress))) -->
2033 [].
2034message(plunit(progress(_UnitTest, Status, _Progress, _Time))) -->
2035 { Status = forall(_Gen,_NthI)
2036 ; Status == assertion
2037 },
2038 !.
2039message(plunit(progress(Unit:Test, Status, Progress, Time))) -->
2040 { jobs(_),
2041 !,
2042 tty_columns(SummaryWidth, Margin),
2043 test_name_summary(Unit:Test, SummaryWidth, NameS),
2044 progress_string(Progress, ProgressS),
2045 progress_tag(Status, Tag, _Keep, Style)
2046 },
2047 [ ansi(Style, '[~w] ~w ~`.t ~w (~3f sec)~*|',
2048 [ProgressS, NameS, Tag, Time.wall, Margin]) ].
2049message(plunit(progress(_UnitTest, Status, _Progress, Time))) -->
2050 { tty_columns(_SummaryWidth, Margin),
2051 progress_tag(Status, Tag, _Keep, Style)
2052 },
2053 [ at_same_line, ansi(Style, '~`.t ~w (~3f sec)~*|',
2054 [Tag, Time.wall, Margin]) ],
2055 ( { tty_feedback }
2056 -> [flush]
2057 ; []
2058 ).
2059message(plunit(failed(Unit:Test, Progress, Line, Failure, _Time, Output))) -->
2060 { unit_file(Unit, File) },
2061 locationprefix(File:Line),
2062 test_name(Unit:Test, Progress),
2063 [': '-[] ],
2064 failure(Failure),
2065 test_output(Output).
2066message(plunit(timeout(Unit:Test, Progress, Line, Limit, Output))) -->
2067 { unit_file(Unit, File) },
2068 locationprefix(File:Line),
2069 test_name(Unit:Test, Progress),
2070 [': '-[] ],
2071 timeout(Limit),
2072 test_output(Output).
2073:- if(swi). 2074message(plunit(failed_assertion(Unit:Test, Line, AssertLoc,
2075 Progress, Reason, Goal))) -->
2076 { unit_file(Unit, File) },
2077 locationprefix(File:Line),
2078 test_name(Unit:Test, Progress),
2079 [ ': assertion'-[] ],
2080 assertion_location(AssertLoc, File),
2081 assertion_reason(Reason), ['\n\t'],
2082 assertion_goal(Unit, Goal).
2083
2084assertion_location(File:Line, File) -->
2085 [ ' at line ~w'-[Line] ].
2086assertion_location(File:Line, _) -->
2087 [ ' at ', url(File:Line) ].
2088assertion_location(unknown, _) -->
2089 [].
2090
2091assertion_reason(fail) -->
2092 !,
2093 [ ' failed'-[] ].
2094assertion_reason(Error) -->
2095 { message_to_string(Error, String) },
2096 [ ' raised "~w"'-[String] ].
2097
2098assertion_goal(Unit, Goal) -->
2099 { unit_module(Unit, Module),
2100 unqualify(Goal, Module, Plain)
2101 },
2102 [ 'Assertion: ~p'-[Plain] ].
2103
2104unqualify(Var, _, Var) :-
2105 var(Var),
2106 !.
2107unqualify(M:Goal, Unit, Goal) :-
2108 nonvar(M),
2109 unit_module(Unit, M),
2110 !.
2111unqualify(M:Goal, _, Goal) :-
2112 callable(Goal),
2113 predicate_property(M:Goal, imported_from(system)),
2114 !.
2115unqualify(Goal, _, Goal).
2116
2117test_output(Msgs-String) -->
2118 { nonvar(Msgs) },
2119 !,
2120 test_output(String).
2121test_output("") --> [].
2122test_output(Output) -->
2123 [ ansi(code, '~N~s', [Output]) ].
2124
2125:- endif. 2126 2127message(plunit(error(Where, Context, _Output, throw(Exception)))) -->
2128 locationprefix(Context),
2129 { message_to_string(Exception, String) },
2130 [ 'error in ~w: ~w'-[Where, String] ].
2131message(plunit(error(Where, Context, _Output, false))) -->
2132 locationprefix(Context),
2133 [ 'setup failed in ~w'-[Where] ].
2134
2135 2136message(plunit(test_output(_, Output))) -->
2137 [ '~s'-[Output] ].
2138 2139:- if(swi). 2140message(interrupt(begin)) -->
2141 { thread_self(Me),
2142 running(Unit, Test, Line, Progress, Me),
2143 !,
2144 unit_file(Unit, File),
2145 restore_output_state
2146 },
2147 [ 'Interrupted test '-[] ],
2148 running(running(Unit:Test, File:Line, Progress, Me)),
2149 [nl],
2150 '$messages':prolog_message(interrupt(begin)).
2151message(interrupt(begin)) -->
2152 '$messages':prolog_message(interrupt(begin)).
2153:- endif. 2154
2155message(concurrent) -->
2156 [ 'concurrent(true) at the level of units is currently ignored.', nl,
2157 'See set_test_options/1 with jobs(Count) for concurrent testing.'
2158 ].
2159
2160test_name(Name, forall(Generator, _Nth-I)/_Total) -->
2161 !,
2162 test_name(Name, -),
2163 [ ' (~d-th forall generator = '-[I],
2164 ansi(code, '~p', [Generator]), ')'-[]
2165 ].
2166test_name(Name, _) -->
2167 !,
2168 [ 'test ', ansi(code, '~q', [Name]) ].
2169
2170running(running(Unit:Test, File:Line, _Progress, Thread)) -->
2171 thread(Thread),
2172 [ '~q:~q at '-[Unit, Test], url(File:Line) ].
2173running([H|T]) -->
2174 ['\t'], running(H),
2175 ( {T == []}
2176 -> []
2177 ; [nl], running(T)
2178 ).
2179
2180thread(main) --> !.
2181thread(Other) -->
2182 [' [~w] '-[Other] ].
2183
2184:- if(swi). 2185write_term(T, OPS) -->
2186 ['~W'-[T,OPS] ].
2187:- else. 2188write_term(T, _OPS) -->
2189 ['~q'-[T]].
2190:- endif. 2191
2192expected_got_ops_(Ex, E, OPS, Goals) -->
2193 [' Expected: '-[]], write_term(Ex, OPS), [nl],
2194 [' Got: '-[]], write_term(E, OPS), [],
2195 ( { Goals = [] } -> []
2196 ; [nl, ' with: '-[]], write_term(Goals, OPS), []
2197 ).
2198
2199
2200failure(List) -->
2201 { is_list(List) },
2202 !,
2203 [ nl ],
2204 failures(List).
2205failure(Var) -->
2206 { var(Var) },
2207 !,
2208 [ 'Unknown failure?' ].
2209failure(succeeded(Time)) -->
2210 !,
2211 [ 'must fail but succeeded in ~2f seconds~n'-[Time] ].
2212failure(wrong_error(Expected, Error)) -->
2213 !,
2214 { copy_term(Expected-Error, Ex-E, Goals),
2215 numbervars(Ex-E-Goals, 0, _),
2216 write_options(OPS)
2217 },
2218 [ 'wrong error'-[], nl ],
2219 expected_got_ops_(Ex, E, OPS, Goals).
2220failure(wrong_answer(cmp(Var, Cmp))) -->
2221 { Cmp =.. [Op,Answer,Expected],
2222 !,
2223 copy_term(Expected-Answer, Ex-A, Goals),
2224 numbervars(Ex-A-Goals, 0, _),
2225 write_options(OPS)
2226 },
2227 [ 'wrong answer for ', ansi(code, '~w', [Var]),
2228 ' (compared using ~w)'-[Op], nl ],
2229 expected_got_ops_(Ex, A, OPS, Goals).
2230failure(wrong_answer(Cmp)) -->
2231 { Cmp =.. [Op,Answer,Expected],
2232 !,
2233 copy_term(Expected-Answer, Ex-A, Goals),
2234 numbervars(Ex-A-Goals, 0, _),
2235 write_options(OPS)
2236 },
2237 [ 'wrong answer (compared using ~w)'-[Op], nl ],
2238 expected_got_ops_(Ex, A, OPS, Goals).
2239failure(wrong_answer(CmpExpected, Bindings)) -->
2240 { ( CmpExpected = all(Cmp)
2241 -> Cmp =.. [_Op1,_,Expected],
2242 Got = Bindings,
2243 Type = all
2244 ; CmpExpected = set(Cmp),
2245 Cmp =.. [_Op2,_,Expected0],
2246 sort(Expected0, Expected),
2247 sort(Bindings, Got),
2248 Type = set
2249 )
2250 },
2251 [ 'wrong "~w" answer:'-[Type] ],
2252 [ nl, ' Expected: ~q'-[Expected] ],
2253 [ nl, ' Found: ~q'-[Got] ].
2254:- if(swi). 2255failure(cmp_error(_Cmp, Error)) -->
2256 { message_to_string(Error, Message) },
2257 [ 'Comparison error: ~w'-[Message] ].
2258failure(throw(Error)) -->
2259 { Error = error(_,_),
2260 !,
2261 message_to_string(Error, Message)
2262 },
2263 [ 'received error: ~w'-[Message] ].
2264:- endif. 2265failure(message) -->
2266 !,
2267 [ 'Generated unexpected warning or error'-[] ].
2268failure(setup_failed(throw(Error))) -->
2269 { Error = error(_,_),
2270 !,
2271 message_to_string(Error, Message)
2272 },
2273 [ 'test setup goal raised error: ~w'-[Message] ].
2274failure(setup_failed(_)) -->
2275 !,
2276 [ 'test setup goal failed' ].
2277failure(Why) -->
2278 [ '~p'-[Why] ].
2279
2280failures([]) -->
2281 !.
2282failures([H|T]) -->
2283 !,
2284 failure(H), [nl],
2285 failures(T).
2286
2287timeout(Limit) -->
2288 [ 'Timeout exceeeded (~2f sec)'-[Limit] ].
2289
2290fixme_message([]) --> [].
2291fixme_message([fixme(Unit, _Name, Line, Reason, How)|T]) -->
2292 { unit_file(Unit, File) },
2293 fixme_message(File:Line, Reason, How),
2294 ( {T == []}
2295 -> []
2296 ; [nl],
2297 fixme_message(T)
2298 ).
2299
2300fixme_message(Location, Reason, failed) -->
2301 [ 'FIXME: ~w: ~w'-[Location, Reason] ].
2302fixme_message(Location, Reason, passed) -->
2303 [ 'FIXME: ~w: passed ~w'-[Location, Reason] ].
2304fixme_message(Location, Reason, nondet) -->
2305 [ 'FIXME: ~w: passed (nondet) ~w'-[Location, Reason] ].
2306
2307
2308write_options([ numbervars(true),
2309 quoted(true),
2310 portray(true),
2311 max_depth(100),
2312 attributes(portray)
2313 ]).
2314
2319
2320test_name_summary(Term, MaxLen, Summary) :-
2321 summary_string(Term, Text),
2322 atom_length(Text, Len),
2323 ( Len =< MaxLen
2324 -> Summary = Text
2325 ; End is MaxLen//2,
2326 Pre is MaxLen - End - 2,
2327 sub_string(Text, 0, Pre, _, PreText),
2328 sub_string(Text, _, End, 0, PostText),
2329 format(string(Summary), '~w..~w', [PreText,PostText])
2330 ).
2331
2332summary_string(Unit:Test, String) =>
2333 summary_string(Test, String1),
2334 atomics_to_string([Unit, String1], :, String).
2335summary_string(@(Name,Vars), String) =>
2336 format(string(String), '~W (using ~W)',
2337 [ Name, [numbervars(true), quoted(false)],
2338 Vars, [numbervars(true), portray(true), quoted(true)]
2339 ]).
2340summary_string(Name, String) =>
2341 term_string(Name, String, [numbervars(true), quoted(false)]).
2342
2346
2347progress_string(forall(_Vars, N-I)/Total, S) =>
2348 format(string(S), '~w-~w/~w', [N,I,Total]).
2349progress_string(Progress, S) =>
2350 term_string(Progress, S).
2351
2357
2358progress_tag(passed, Tag, Keep, Style) =>
2359 Tag = passed, Keep = false, Style = comment.
2360progress_tag(fixme(passed), Tag, Keep, Style) =>
2361 Tag = passed, Keep = false, Style = comment.
2362progress_tag(fixme(_), Tag, Keep, Style) =>
2363 Tag = fixme, Keep = true, Style = warning.
2364progress_tag(nondet, Tag, Keep, Style) =>
2365 Tag = '**NONDET', Keep = true, Style = warning.
2366progress_tag(timeout(_Limit), Tag, Keep, Style) =>
2367 Tag = '**TIMEOUT', Keep = true, Style = warning.
2368progress_tag(assertion, Tag, Keep, Style) =>
2369 Tag = '**FAILED', Keep = true, Style = error.
2370progress_tag(failed, Tag, Keep, Style) =>
2371 Tag = '**FAILED', Keep = true, Style = error.
2372progress_tag(forall(_,0), Tag, Keep, Style) =>
2373 Tag = passed, Keep = false, Style = comment.
2374progress_tag(forall(_,_), Tag, Keep, Style) =>
2375 Tag = '**FAILED', Keep = true, Style = error.
2376
2377
2378 2381
2382save_output_state :-
2383 stream_property(Output, alias(user_output)),
2384 stream_property(Error, alias(user_error)),
2385 asserta(output_streams(Output, Error)).
2386
2387restore_output_state :-
2388 output_streams(Output, Error),
2389 !,
2390 set_stream(Output, alias(user_output)),
2391 set_stream(Error, alias(user_error)).
2392restore_output_state.
2393
2394
2395
2396 2399
2405
2406:- dynamic
2407 jobs/1, 2408 job_window/1, 2409 job_status_line/3. 2410
2411job_feedback(_, jobs(Jobs)) :-
2412 retractall(jobs(_)),
2413 Jobs > 1,
2414 asserta(jobs(Jobs)),
2415 tty_feedback,
2416 !,
2417 retractall(job_window(_)),
2418 asserta(job_window(Jobs)),
2419 retractall(job_status_line(_,_,_)),
2420 jobs_redraw.
2421job_feedback(_, jobs(Jobs)) :-
2422 !,
2423 retractall(job_window(_)),
2424 info(plunit(jobs(Jobs))).
2425job_feedback(_, Msg) :-
2426 job_window(_),
2427 !,
2428 with_mutex(plunit_feedback, job_feedback(Msg)).
2429job_feedback(Level, Msg) :-
2430 print_message(Level, plunit(Msg)).
2431
2432job_feedback(begin(Unit:Test, _Location, Progress)) =>
2433 tty_columns(SummaryWidth, _Margin),
2434 test_name_summary(Unit:Test, SummaryWidth, NameS),
2435 progress_string(Progress, ProgressS),
2436 tty_clear_to_eol(CE),
2437 job_format(comment, '\r[~w] ~w ..~w',
2438 [ProgressS, NameS, CE]),
2439 flush_output.
2440job_feedback(end(_UnitTest, _Location, _Progress)) =>
2441 true.
2442job_feedback(progress(_UnitTest, Status, _Progress, Time)) =>
2443 ( hide_progress(Status)
2444 -> true
2445 ; tty_columns(_SummaryWidth, Margin),
2446 progress_tag(Status, Tag, _Keep, Style),
2447 job_finish(Style, '~`.t ~w (~3f sec)~*|',
2448 [Tag, Time.wall, Margin])
2449 ).
2450job_feedback(failed(UnitTest, Progress, Line, Error, Time, Output)) =>
2451 tty_columns(_SummaryWidth, Margin),
2452 progress_tag(failed, Tag, _Keep, Style),
2453 job_finish(Style, '~`.t ~w (~3f sec)~*|',
2454 [Tag, Time.wall, Margin]),
2455 print_test_output(Error, Output),
2456 ( ( Error = timeout(_) 2457 ; Error == assertion 2458 )
2459 -> true
2460 ; print_message(Style, plunit(failed(UnitTest, Progress, Line,
2461 Error, Time, "")))
2462 ),
2463 jobs_redraw.
2464job_feedback(begin(_Unit)) => true.
2465job_feedback(end(_Unit, _Summary)) => true.
2466
2467hide_progress(assertion).
2468hide_progress(forall(_,_)).
2469hide_progress(failed).
2470hide_progress(timeout(_)).
2471
2472print_test_output(Error, _Msgs-Output) =>
2473 print_test_output(Error, Output).
2474print_test_output(_, "") => true.
2475print_test_output(assertion, Output) =>
2476 print_message(debug, plunit(test_output(error, Output))).
2477print_test_output(message, Output) =>
2478 print_message(debug, plunit(test_output(error, Output))).
2479print_test_output(_, Output) =>
2480 print_message(debug, plunit(test_output(informational, Output))).
2481
2485
2486jobs_redraw :-
2487 job_window(N),
2488 !,
2489 tty_columns(_, Width),
2490 tty_header_line(Width),
2491 forall(between(1,N,Line), job_redraw_worker(Line)),
2492 tty_header_line(Width).
2493jobs_redraw.
2494
2495job_redraw_worker(Line) :-
2496 ( job_status_line(Line, Fmt, Args)
2497 -> ansi_format(comment, Fmt, Args)
2498 ; true
2499 ),
2500 nl.
2501
2507
2508job_format(Style, Fmt, Args) :-
2509 job_self(Job),
2510 job_format(Job, Style, Fmt, Args, true).
2511
2517
2518job_finish(Style, Fmt, Args) :-
2519 job_self(Job),
2520 job_finish(Job, Style, Fmt, Args).
2521
2522:- det(job_finish/4). 2523job_finish(Job, Style, Fmt, Args) :-
2524 retract(job_status_line(Job, Fmt0, Args0)),
2525 !,
2526 string_concat(Fmt0, Fmt, Fmt1),
2527 append(Args0, Args, Args1),
2528 job_format(Job, Style, Fmt1, Args1, false).
2529
2530:- det(job_format/5). 2531job_format(Job, Style, Fmt, Args, Save) :-
2532 job_window(Jobs),
2533 Up is Jobs+2-Job,
2534 flush_output(user_output),
2535 tty_up_and_clear(Up),
2536 ansi_format(Style, Fmt, Args),
2537 ( Save == true
2538 -> retractall(job_status_line(Job, _, _)),
2539 asserta(job_status_line(Job, Fmt, Args))
2540 ; true
2541 ),
2542 tty_down_and_home(Up),
2543 flush_output(user_output).
2544
2545:- det(job_self/1). 2546job_self(Job) :-
2547 job_window(N),
2548 N > 1,
2549 thread_self(Me),
2550 split_string(Me, '_', '', [_,_,S]),
2551 number_string(Job, S).
2552
2557
2558tty_feedback :-
2559 has_tty,
2560 current_test_flag(format, tty).
2561
2562has_tty :-
2563 stream_property(user_output, tty(true)).
2564
2565tty_columns(SummaryWidth, Margin) :-
2566 tty_width(W),
2567 Margin is W-8,
2568 SummaryWidth is max(20,Margin-34).
2569
2570tty_width(W) :-
2571 current_predicate(tty_size/2),
2572 catch(tty_size(_Rows, Cols), error(_,_), fail),
2573 Cols > 25,
2574 !,
2575 W = Cols.
2576tty_width(80).
2577
(Width) :-
2579 ansi_format(comment, '~N~`\u2015t~*|~n', [Width]).
2580
2581:- if(current_predicate(tty_get_capability/3)). 2582tty_clear_to_eol(S) :-
2583 getenv('TERM', _),
2584 catch(tty_get_capability(ce, string, S),
2585 error(_,_),
2586 fail),
2587 !.
2588:- endif. 2589tty_clear_to_eol('\e[K').
2590
2591tty_up_and_clear(Lines) :-
2592 format(user_output, '\e[~dA\r\e[K', [Lines]).
2593
2594tty_down_and_home(Lines) :-
2595 format(user_output, '\e[~dB\r', [Lines]).
2596
2597:- if(swi). 2598
2599:- multifile
2600 prolog:message/3,
2601 prolog:message_action/2. 2602
2603prolog:message(Term) -->
2604 message(Term).
2605
2607
2608prolog:message_action(make(done(Files)), _) :-
2609 make_run_tests(Files).
2610
2611:- endif. 2612
2613:- if(sicstus). 2614
2615user:generate_message_hook(Message) -->
2616 message(Message),
2617 [nl]. 2618
2625
2626user:message_hook(informational, plunit(begin(Unit)), _Lines) :-
2627 format(user_error, '% PL-Unit: ~w ', [Unit]),
2628 flush_output(user_error).
2629user:message_hook(informational, plunit(end(_Unit)), _Lines) :-
2630 format(user, ' done~n', []).
2631
2632:- endif. 2633
2634 2637
2638'$nowarn_autoload'(set_test_options/1, _).
2639'$nowarn_autoload'(run_tests/0, _).
2640'$nowarn_autoload'(run_tests/1, _).
2641'$nowarn_autoload'(run_tests/2, _).
2642'$nowarn_autoload'(running_tests/0, _).
2643'$nowarn_autoload'(current_test/5, _).
2644'$nowarn_autoload'(current_test_unit/2, _).
2645'$nowarn_autoload'(test_report/1, _)