1 % (c) 2009-2026 Lehrstuhl fuer Softwaretechnik und Programmiersprachen,
2 % Heinrich Heine Universitaet Duesseldorf
3 % This software is licenced under EPL 1.0 (http://www.eclipse.org/org/documents/epl-v10.html)
4
5 %:- use_module('../extensions/profiler/profiler.pl').
6
7 :- module(test_runner, [
8 test_repl/0,
9 run_silently/0,
10 run_safely/0,
11 run_last_test/0, last/0,
12 run_tests_by_id/1, ids/1, run_id/1,
13 run_tests_all/0, run_tests_all_except/1,
14 run_tests_by_category/1, run_tests_by_category/2, category/1,
15 run_tests_by_first_category/1,
16 makefile_by_category/2, copy/1,
17 generate_makefile_all_tests/0,
18 generate_makefile_for_coverage/0,
19 full_flush/0,
20 jenkins_sanity_check/0,
21 sanity_check/1,
22 v/0, vv/0,
23 cache/0, % enable caching
24 all_categories/1,
25 all_ids/1,
26 ids_in_category/2,
27 set_prob_examples_location/1,
28 halt_tests/0 % use to call halt with proper exit code; however, normally test predicates will call halt1 directly, mainly useful in junit mode
29 ]).
30
31 :- if(predicate_property(expects_dialect(_), _)).
32 :- expects_dialect(sicstus4).
33 :- endif.
34
35 % Some errors, such as syntax errors, are only printed through the message mechanism and not thrown as exceptions.
36 % These errors also don't terminate SICStus or affect the exit code,
37 % which makes it easy for them to go unnoticed in CI runs.
38 % As a workaround, add a portray_message hook to detect error messages
39 % and halt the test runner at an appropriate time.
40
41 :- dynamic(prolog_error_occurred/0).
42
43 :- multifile(user:portray_message/2).
44 user:portray_message(error, _) :-
45 \+ prolog_error_occurred,
46 assertz(prolog_error_occurred),
47 fail. % to let SICStus portray the error
48
49 check_no_prolog_startup_error :-
50 prolog_error_occurred,
51 !,
52 format('*** Error(s) from Prolog while starting test runner! Aborting. ***~n', []),
53 halt(1).
54 check_no_prolog_startup_error.
55 :- initialization(check_no_prolog_startup_error).
56
57 :- use_module('../src/pathes', []). % set up library search paths
58
59 % comment in to ensure that plspec loaded first:
60 % :- use_module('../extensions/plspec/plspec/plspec_core').
61
62 :- use_module(probsrc(prob_cli)). % we call go_cli
63
64 %:- set_prolog_flag(compiling,debugcode).
65 %:- set_prolog_flag(source_info,on).
66 %:- set_prolog_flag(profiling,on).
67
68 /*
69 :- use_module('../extensions/profiler/profiler.pl'). % (adds the profiler himself)
70 :- use_module('../extensions/profiler/profiler_te.pl'). % (adds the term expander)
71 %:- use_module('../extensions/profiler/profiler_gui.pl'). % (adds the term expander)
72 :- enable_profiling_all(b_expression_sharing).
73 :- enable_profiling(bsyntaxtree:transform_bexpr_with_acc/5).
74 :- enable_profiling(bsyntaxtree:transform_bexpr/3).
75 :- enable_profiling(b_ast_cleanup:recompute_used_ids_info/2).
76 :- enable_profiling(bsyntaxtree:sub_expression_contains_wd_condition/1).
77
78 for starting from Spider:
79 set_prob_examples_location('../../prob_examples'), run_silently, test_repl.
80 or use test_runner_cov.pl
81 */
82
83
84 :- use_module(library(system)).
85 :- use_module(library(lists)).
86 :- use_module(library(sets), [intersect/2]).
87 :- use_module(library(file_systems)).
88
89 :- use_module(probsrc(junit_tests),[set_junit_dir/1,create_and_print_junit_result/4]).
90 :- use_module(testcases).
91 :- use_module(probsrc(system_call)).
92 :- use_module(probsrc(tools),[safe_number_codes/2,get_options/5]).
93 :- use_module(probsrc(tools_commands),[edit_file/1]).
94 :- use_module(probsrc(tools_printing), [start_terminal_colour/2, reset_terminal_colour/1, format_with_colour/4, format_with_colour_nl/4]).
95 :- use_module(probsrc(error_manager),[get_total_number_of_errors/1, get_all_errors/1]).
96 :- use_module(probsrc(debug),[formatsilent/3, debug_mode/1]).
97 :- use_module(probsrc(performance_messages),[toggle_perfmessages/0]).
98
99 :- use_module(probsrc(module_information)).
100 :- module_info(group,testing).
101 :- module_info(description,'This module runs the tests stored in testcases.pl.').
102
103 :- set_prolog_flag(double_quotes, codes).
104
105
106 :- use_module(probsrc(tools), [ajoin_with_sep/3]).
107 generate_makefile(RegenerateGoal,Filename,TargetCommand) :-
108 tell(Filename),
109 all_first_categories(AllTestCategories),
110 ajoin_with_sep(AllTestCategories, ' \\\n\t', JoinedCategories),
111 write('# This Makefile is generated automatically. DO NOT EDIT.\n'),
112 write('# If you have added/removed a test category, regenerate using this command:\n'),
113 format('# ./prolog.sh --file tests/test_runner.pl --goal "~q, halt ; halt(1)."\n\n', [RegenerateGoal]),
114 format('categories = \\\n\t~w\n\n', [JoinedCategories]),
115 write('.PHONY: test_all_source\n'),
116 write('test_all_source: $(categories)\n\n'),
117 write('.PHONY: $(categories)\n'),
118 format('$(categories):\n\t~w\n', [TargetCommand]),
119 told,
120 format(user_output,'Generated Makefile: ~w~n',[Filename]).
121
122 %write_subtargets([G]) :- write(G).
123 %write_subtargets([G|Gs]) :-
124 % write(G), write(' '),
125 % write_subtargets(Gs).
126
127 generate_makefile_all_tests :-
128 % run tests where category G is the first category to avoid running tests multiple times
129 % also avoids concurrency issues when test run multiple times in parallel with diff checking of output
130 generate_makefile(generate_makefile_all_tests, 'tests/Makefile_All_Tests',
131 % Makefile_All_Tests is (indirectly) included from the top-level Makefile,
132 % so the working directory is the repository root
133 % and the test_runner.pl path must include the tests/ directory prefix.
134 './prolog.sh --file tests/test_runner.pl --goal "run_silently, run_tests_by_first_category($@), halt_tests ; halt(1)."').
135
136 :- use_module(probsrc(tools_platform), [host_platform/1]).
137 % TODO Do we want to install SWI-Prolog on all CI runners?
138 group_cannot_be_checked_on_ci_server(setlog).
139 group_cannot_be_checked_on_ci_server(smt_solver_integration) :-
140 host_platform(windows). % TODO Install Z3 on GitLab CI Windows runner
141 group_cannot_be_checked_on_ci_server(cdclt) :-
142 \+ (current_prolog_flag(dialect, sicstus),
143 current_prolog_flag(version_data, sicstus(4,VN,VM,_,_)),
144 VN>=10, VM >= 2). % disable cdclt tests due to segmentation faults (SPRM-21543), fixed in 4.10.2
145
146 generate_makefile_for_coverage :-
147 generate_makefile(generate_makefile_for_coverage, 'Makefile_Coverage_Groups', './prolog.sh --file tests/prob_cov_runner.pl --goal "coverage_group_data($@), halt ; halt(1)."').
148
149 all_first_categories(X) :- % only categories that appear as first category
150 findall(Group1,
151 cli_testcase(_Id,[Group1|_],_Conf,_Args,_Desc),
152 ListOfGroups),
153 remove_dups(ListOfGroups,X).
154 all_categories(X) :-
155 findall(Groups,
156 cli_testcase(_Id,Groups,_Conf,_Args,_Desc),
157 List),
158 append(List,ListOfGroups),
159 remove_dups(ListOfGroups,X).
160
161 all_ids(X) :-
162 findall(Id,
163 cli_testcase(Id,_Groups,_Conf,_Args,_Desc),
164 List),
165 remove_dups(List,X).
166
167 ids_in_category(Category,IDs) :-
168 findall(Id,
169 (cli_testcase(Id,Groups,_Conf,_Args,_Desc),member(Category,Groups)),
170 List),
171 remove_dups(List,IDs).
172
173 prob_junit_dir(JUnitDir) :- environ('PROB_JUNIT_DIR', JUnitDir).
174
175 prob_junit_args(JUnitArgs) :-
176 prob_junit_dir(JUnitDir), !,
177 JUnitArgs = ['-junit', JUnitDir].
178 prob_junit_args([]).
179
180 halt1_allowed :- \+ repl_mode.
181
182 tests_multiply_timeout(Var) :-
183 environ('TESTS_MULTIPLY_TIMEOUT', Var2), !, tools:arg_is_number(Var2,Var).
184 tests_multiply_timeout(Var) :- multiply_timeout(Var).
185
186 :- dynamic multiply_timeout/1.
187
188 % call updir from within Spider, when you are in the src subdirectory
189 set_cur_dir :- (directory_exists('./src') -> true /* we seem to be in the right directory */
190 ; directory_exists('./cia') -> current_directory(_Old,'./..')
191 ; print('Please start tests from ProB directory or ProB/src directory'),nl,
192 print('Current directory: '),
193 current_directory(CD), print(CD), nl).
194
195 reset_test_runner(SessionInfo) :-
196 reset_nr_of_tests, set_cur_dir,
197 retractall(test_skipped(_)), retractall(test_failed(_)), retractall(last_test_failed(_)),
198 retractall(test_diff_failed(_,_,_)),
199 statistics(walltime,[WStart,_]),
200 bb_put(reset_test_runner_wtime,WStart),
201 bb_put(reset_test_runner_info,SessionInfo).
202
203
204 ids(Nr) :- show_command(Nr).
205 show_command(Nr) :- cli_testcase(Nr,_,_,L,Desc),
206 print('# '), print(Desc),nl, l_pr([probcli|L]).
207 l_pr([]) :- nl.
208 l_pr([H|T]) :- print(' '),print(H), l_pr(T).
209
210 :- volatile sanity_check_failed/0.
211 :- dynamic sanity_check_failed/0.
212 jenkins_sanity_check :-
213 sanity_check(true),
214 (sanity_check_failed -> halt1 ; halt(0)).
215 sanity_check(_Jenkins) :-
216 cli_testcase(Id,Categories,_,Args,_Comm1),
217 \+ member('-strict',Args),
218 format_warning('*** test does not use -strict option: ',[]), print_test(Id,Categories),nl,
219 assertz(sanity_check_failed), fail.
220 sanity_check(Jenkins) :-
221 Jenkins == false,
222 cli_testcase_diff_check_output(Id,_F1,_F2),
223 cli_testcase(Id,Categories,_I1,_A1,_Comm1),
224 (Categories = [_]
225 -> true
226 ; format_warning('*** multiple categories for test with output file; can generate race conditions when run in parallel: ',[]),
227 print_test(Id,Categories),
228 nl /* can generate race conditions when run in parallel */),
229 assertz(sanity_check_failed), fail.
230 sanity_check(_Jenkins) :-
231 cli_testcase_diff_check_output(Id,_F1,_F2),
232 \+ (cli_testcase(Id,_Categories,_I1,_A1,_Comm1)),
233 format_warning_nl('*** no cli_testcase, but diff output defined for id: ~w',[Id]),
234 assertz(sanity_check_failed), fail.
235 sanity_check(_Jenkins) :-
236 cli_testcase(Id,C1,I1,A1,Comm1),
237 cli_testcase(Id,C2,I2,A2,Comm2),
238 [C1,I1,A1,Comm1] \= [C2,I2,A2,Comm2],
239 format_warning_nl('*** multiple cli_testcases for id: ~w',[Id]),
240 assertz(sanity_check_failed), fail.
241 sanity_check(_Jenkins).
242
243
244 format_error_nl(F,Args) :- format_with_colour_nl(user_output,[red,bold],F,Args).
245 format_warning(F,Args) :- format_with_colour(user_output,[red],F,Args).
246 format_warning_nl(F,Args) :- format_with_colour_nl(user_output,[red],F,Args).
247 format_progress_nl(F,Args) :- format_with_colour_nl(user_output,[blue],F,Args).
248
249 print_test(Id,Comment) :- print(Id),print(' : '), print(Comment).
250
251 % run the latest test (with highest id)
252 last :- run_last_test.
253 run_last_test :- get_last_test_id(Id),
254 run_tests_by_id(Id,_,no_skipping).
255
256 get_last_test_id(Id) :- set_last_test_id, last_test_id(Id).
257
258 set_last_test_id :-
259 retractall(last_test_id(_)), assertz(last_test_id(-1)),
260 cli_testcase(Id,C1,I1,A1,Comm1),
261 (cli_testcase(Id,C2,I2,A2,Comm2),
262 (C1,I1,A1,Comm1) \= (C2,I2,A2,Comm2)
263 -> format_warning_nl('~n*** multiple entries for test id: ~w',[Id])
264 ; true),
265 update_last(Id),
266 fail.
267 set_last_test_id.
268
269 :- volatile last_test_id/1.
270 :- dynamic last_test_id/1.
271 update_last(Id) :- number(Id),!, % debug_print(9,Id), debug_print(9,' '),
272 retract(last_test_id(L)),
273 (Id>L -> Max = Id ; Max = L),
274 assertz(last_test_id(Max)).
275 update_last(Id) :- format_warning_nl('~n*** test id not a number: ~w',[Id]).
276
277 repeat_id(ID,Nr) :- repeat_id_aux(ID,0,Nr,success,10000000,0,0).
278 repeat_id_aux(ID,Nr,TotNr,Status1,Min,Max,Tot) :- Nr<TotNr, !, N1 is Nr+1,
279 statistics(walltime,[Start,_]),
280 run_tests_by_id(ID,Status,no_skipping),
281 (Status=success -> Status2=Status1, Col=blue ; Status2=Status, Col=red),
282 statistics(walltime,[Stop,_]),
283 WT is Stop - Start,
284 NewMin is min(Min,WT), NewMax is max(Max,WT), NewTot is Tot+WT,
285 Average is NewTot / N1,
286 format_with_colour_nl(user_output,[Col],'Test ~w repeated ~w/~w times~n Walltime Minumum = ~w ms, Maximum = ~w ms, Average = ~w ms~n Status=~w',[ID,N1,TotNr,NewMin,NewMax,Average,Status]),
287 repeat_id_aux(ID,N1,TotNr,Status2,NewMin,NewMax,NewTot).
288 repeat_id_aux(_,_,_TotNr,_Status,_Min,_Max,_).
289
290 % run a test with a specific id
291 run_id(X) :- run_tests_by_id(X,_,no_skipping).
292 run_tests_by_id(X) :- run_tests_by_id(X,_,allow_skipping).
293 run_tests_by_id(X,Status,AllowSkipping) :- reset_test_runner(id(X)),
294 phrase(tests_by_id(X), Testcases),
295 run_list(Testcases, AllowSkipping),
296 check_failed(Status).
297 tests_by_id([]) --> [].
298 tests_by_id(From-To) --> !,
299 ({From>To} -> []
300 ; tests_by_id(From), {F1 is From+1},
301 tests_by_id(F1-To)).
302 tests_by_id([Id | Ids]) --> !,
303 tests_by_id(Id),
304 tests_by_id(Ids).
305 tests_by_id(Id) -->
306 {cli_testcase(Id,TestCategories,TestInfos,Arguments,Comment)}, !,
307 [testcase(Id,TestCategories,TestInfos,Arguments,Comment)].
308 tests_by_id(Id) -->
309 {\+(cli_testcase(Id,_Category,_Infos,_Arguments,_Comment))}, !,
310 {format_warning_nl('*** No testcase with ID ~w found', [Id])}.
311
312 :- use_module(library(random),[random_select/3]).
313 run_random_tests(Nr) :-
314 findall(testcase(Id,TestCategories,TestInfos,Arguments,Comment),
315 cli_testcase(Id,TestCategories,TestInfos,Arguments,Comment),AllTests),
316 select_random_tests(Nr,AllTests,Tests),
317 reset_test_runner(random(Nr)),
318 run_list(Tests), check_failed(_).
319 select_random_tests(N,_,[]) :- N<1,!.
320 select_random_tests(_,[],[]) :- !.
321 select_random_tests(N,All,[X|Tests]) :-
322 random_select(X,All,Rest),
323 N1 is N-1,
324 select_random_tests(N1,Rest,Tests).
325
326
327 run_tests_all :- run_tests_all_except([]).
328
329 :- use_module(library(ordsets)).
330 run_tests_all_except(Categories) :- reset_test_runner(all_except(Categories)),
331 findall(Test, test_not_in_categories(Categories, Test), Tests),
332 run_list(Tests),
333 check_failed(_).
334
335 test_not_in_categories(Categories, Test) :-
336 sort(Categories, SC),
337 test_not_in_categories_aux(SC, Test).
338
339 :- use_module(library(ordsets), [ord_intersect/2]).
340 test_not_in_categories_aux(SC, testcase(Id,TestCategories,Infos,Arguments,Comment)) :-
341 cli_testcase(Id,TestCategories,Infos,Arguments,Comment),
342 sort(TestCategories,TC),
343 \+ ord_intersect(TC,SC).
344
345
346 :- dynamic silent_running/0, no_strict_running/0.
347 run_silently :- silent_running, !.
348 run_silently :- add_additional_arguments(['-silent']), assertz(silent_running).
349 run_no_strict :- (no_strict_running -> true ; assertz(no_strict_running)). % useful to see all errors of a test
350
351 % perform additional checks (e.g., used_ids info in AST) and throw errors when something is wrong
352 run_safely :- add_additional_preference('PROB_SAFE_MODE','TRUE').
353
354 % run all tests with a specific category
355 category(X) :- run_tests_by_category(X).
356 run_tests_by_category(X) :- run_tests_by_category(X,all).
357 run_tests_by_first_category(X) :- % used as entry in Jenkins when running all tests in parallel by category
358 run_tests_by_category(X,first).
359 run_tests_by_category(X,FirstOnly) :-
360 reset_test_runner(category(X,FirstOnly)),
361 (is_list(X) -> run_tests_by_category_aux(X,FirstOnly) ; run_tests_by_category_aux([X],FirstOnly)),
362 check_failed(_).
363 run_tests_by_category_aux(Categories,FirstOnly) :-
364 get_tests_for_categories(Categories,FirstOnly,List),
365 ( List=[] -> format_warning_nl('*** No testcase with categories ~w found', [Categories])
366 ; run_list(List)).
367
368 get_tests_for_categories(Categories,List) :-
369 get_tests_for_categories(Categories,all,List).
370 get_tests_for_categories(Categories,FirstOnly,List) :-
371 findall(testcase(Id, TestCategories, Infos, Arguments, Comment),
372 (cli_testcase(Id, TestCategories, Infos, Arguments, Comment),
373 (FirstOnly=first -> TestCategories=[C1|_], member(C1,Categories)
374 ; intersect(Categories, TestCategories)) ),
375 List).
376
377 run_tests_using_command(Command) :- reset_test_runner(cmd(Command)),
378 findall(testcase(Id, TestCategories, Infos, Arguments, Comment),
379 (cli_testcase(Id, TestCategories, Infos, Arguments, Comment),
380 member(Command, Arguments)),
381 List),
382 ( List=[] -> format_warning_nl('*** No testcase using command ~w found', [Command])
383 ; run_list(List), check_failed(_)).
384
385 run_tests_using_preference(Pref,Val) :- reset_test_runner(using_pref(Pref,Val)),
386 findall(testcase(Id, TestCategories, Infos, Arguments, Comment),
387 (cli_testcase(Id, TestCategories, Infos, Arguments, Comment),
388 append(_,['-p',CmdPref,Val|_],Arguments),
389 match_preference(Pref,CmdPref) ),
390 List),
391 ( List=[] -> format_warning_nl('*** No testcase using preference ~w with value ~w found', [Pref,Val])
392 ; run_list(List), check_failed(_)).
393
394 :- use_module(probsrc(preferences),[eclipse_preference/2]).
395 match_preference(A,A).
396 match_preference(A,B) :- eclipse_preference(A,B) ; eclipse_preference(B,A).
397
398 % Generate file list (for copying) of a category :
399 show_files(Cat) :-
400 cli_testcase(Id, TestCategories, _Infos, Arguments, _Comment),
401 member(Cat, TestCategories), % print(Arguments),nl,
402 ( file_in_arguments(File,Arguments)
403 ;
404 get_testcase_diff_check_output(Id,_GeneratedFile,File)),
405 format('~w ',[File]),
406 fail.
407 show_files(_) :- nl.
408
409 file_in_arguments(F,['-p',_,_|T]) :- !, file_in_arguments(F,T).
410 file_in_arguments(F,[C,_|T]) :- binary_command(C),!, file_in_arguments(F,T).
411 file_in_arguments(F,[H|T]) :- is_file(H),H=F ; file_in_arguments(F,T).
412 binary_command(eval). binary_command(evalt). binary_command(evalf).
413 binary_command('-mc').
414 is_file(F) :- atom(F), atom_codes(F,Codes), member(47,Codes),!.
415
416
417 % Generate a Makefile for all listed Categories
418 % example: makefile_by_category('AlstomMakefile',[animate,history,sptxt,rel_fnc])
419 % the Makefile can be run to perform the listed tests on a compiled version of probcli
420 makefile_by_category(File, Categories) :-
421 (is_list(Categories) -> Cats = Categories ; Cats = [Categories]),
422 my_open(File, Stream),
423 format(Stream, 'PROBCLI=probcli~n',[]),
424 format(Stream, 'test_all:', []),
425 makefile_write_categories(Stream, Cats),
426 makefile_by_category_aux(Stream, Cats),
427 my_close(Stream).
428 makefile_by_category_aux(_Stream, []).
429 makefile_by_category_aux(Stream, [Cat | Cats]) :-
430 makefile_by_category_single(Stream, Cat),
431 makefile_by_category_aux(Stream, Cats).
432 makefile_by_category_single(Stream, Cat) :-
433 findall(testcase(Id, TestCategories, Infos, Arguments, Comment),
434 (cli_testcase(Id, TestCategories, Infos, Arguments, Comment),
435 member(Cat, TestCategories)),
436 List),
437 (List=[] -> format_warning_nl('*** No testcase with category ~w found', [Cat])
438 ; format(Stream, '~n~w:~n', [Cat]), makefile_write_calls(Stream, List)).
439
440 my_open(user_output,S) :- !, S=user_output.
441 my_open(File,S) :- open(File,write,S).
442 my_close(user_output) :- !.
443 my_close(S) :- close(S).
444
445 makefile_write_categories(Stream, []) :-
446 format(Stream, '~n', []).
447 makefile_write_categories(Stream, [Cat | Cats]) :-
448 format(Stream, ' ~a', [Cat]),
449 makefile_write_categories(Stream, Cats).
450
451 makefile_write_calls(_Stream, []).
452 makefile_write_calls(Stream, [testcase(Id, _TestCategories, _Infos, Arguments, Comment) | Tests]) :-
453 (Comment='' -> true ; format(Stream,'\techo \"Test ~w : ~w\"~n',[Id,Comment])),
454 format(Stream, '\t$(PROBCLI)', []),
455 makefile_write_arguments(Stream, Arguments),
456 makefile_write_diff(Stream, Id),
457 makefile_write_calls(Stream, Tests).
458
459 makefile_write_arguments(Stream, []) :-
460 format(Stream, '~n', []).
461 makefile_write_arguments(Stream, [Arg | Args]) :-
462 format(Stream, ' ~w', [Arg]),
463 (quote_next_arg(Arg) -> makefile_write_arguments_quoted(Stream,Args)
464 ; makefile_write_arguments(Stream, Args)).
465
466 quote_next_arg('-goal'). % this will contain spaces ,... surround in "" for shell
467 quote_next_arg('--check_goal').
468 quote_next_arg('-check_goal').
469 quote_next_arg('-cbc_deadlock_pred').
470 quote_next_arg('-eval').
471 quote_next_arg('-evalt').
472 quote_next_arg('-evalf').
473 quote_next_arg('-cbc_sequence_with_target'). % actually quotes next two !
474 quote_next_arg('-cbc_sequence_with_target_all'). % ditto <- TO DO
475
476
477 makefile_write_arguments_quoted(Stream, []) :-
478 format(Stream, '~n', []).
479 makefile_write_arguments_quoted(Stream, [Arg | Args]) :-
480 format(Stream, ' \"~w\"', [Arg]),
481 makefile_write_arguments(Stream, Args).
482
483 makefile_write_diff(Stream, ID) :-
484 get_testcase_diff_check_output(ID, File1, File2),
485 format(Stream, '\tdiff -b ~w ~w~n', [File1, File2]),
486 fail.
487 makefile_write_diff(_Stream, _ID).
488
489 % -------------------------
490
491 copy(Cat) :- (Cat=[_|_] -> C=Cat ; C=[Cat]),
492 generate_copy_commands(C,'testarchive/').
493
494 :- use_module(probsrc(b_trace_checking),[get_default_trace_file/2]).
495 generate_copy_commands(Categories,Dest) :-
496 cli_testcase(ID, TestCategories, _Infos, Arguments, _Comment),
497 non_empty_inter(Categories,TestCategories), %print(ID),nl,
498 Arguments=[MainFile|_], generate_copy_command(MainFile,Dest), % print(MainFile),nl,
499 additional_testcase_file(ID,MainFile,Arguments,ExtraFile),
500 generate_copy_command(ExtraFile,Dest),
501 fail.
502 generate_copy_commands(_,_).
503
504 additional_testcase_file(ID,_,_,EFile) :- extra_testcase_file(ID,EFile).
505 additional_testcase_file(_ID,File,Arguments,TFile) :- member('-t',Arguments),
506 get_default_trace_file(File,TFile).
507 additional_testcase_file(ID,_,_,RefFile2) :- get_testcase_diff_check_output(ID,_File1,RefFile2).
508
509 non_empty_inter(A,B) :- member(X,A), member(X,B),!.
510
511 :- use_module(probsrc(tools_strings),[string_concatenate/3]).
512 :- use_module(probsrc(tools),[get_parent_directory/2]).
513 generate_copy_command(File,Dest) :-
514 safe_file_exists(File),
515 get_parent_directory(File,Dir),!,
516 string_concatenate(Dest,Dir,DestDir),
517 string_concatenate(Dest,File,DestFile),
518 format(user_output,'\tmkdir -p ~w~n',[DestDir]),
519 get_command_path(mkdir,MkCmdPath),
520 system_call(MkCmdPath, ['-p',DestDir],_Text1,_JExit1),
521 format(user_output,'\tcp ~w ~w~n',[File,DestFile]),
522 get_command_path(cp,CpCmdPath),
523 system_call(CpCmdPath, [File,DestFile],_Text2,_JExit2).
524 generate_copy_command(_,_).
525
526 % -------------------------
527
528 :- dynamic test_failed/1, last_test_failed/1, test_diff_failed/3, test_skipped/1.
529 halt_tests :-
530 prolog_error_occurred,
531 !,
532 halt1.
533 halt_tests :- test_failed(_),!,
534 halt1.
535 halt_tests :-
536 nl,print('TEST RUN SUCCESSFUL'),nl,
537 halt. % regular halt
538 halt1 :-
539 format_error_nl('TEST RUN FAILED',[]),
540 halt(1).
541
542 check_failed(failure) :- test_failed(X),!,print_failed_tests,
543 print('Use the following command to run individual tests: '),nl,
544 print(' ./prolog.sh --file tests/test_runner.pl --goal "run_id('),print(X),print(')."'),nl,
545 (halt1_allowed -> halt1 ; print('halt(1) :: dontstop mode'),nl).
546 check_failed(success) :- number_of_tests_run(Nr),
547 start_terminal_colour([green,bold],user_output),
548 findall(Y,test_skipped(Y),Skips), length(Skips,NrSkips),
549 bb_get(reset_test_runner_info,Info),
550 (Nr=1,NrSkips=0,Info\=category(_,_) -> format(user_output,'Test successful.~n',[])
551 ; NrSkips>0 -> format(user_output,'All ~w tests successful, ~w skipped (for ~w).~n',[Nr,NrSkips,Info])
552 ; format(user_output,'All ~w tests successful (for ~w).~n',[Nr,Info])),
553 reset_terminal_colour(user_output).
554 print_failed_tests :- number_of_tests_run(Nr),
555 findall(Y,test_failed(Y),Fails), length(Fails,NrFails),
556 findall(Y,test_skipped(Y),Skips), length(Skips,NrSkips),
557 start_terminal_colour([red,bold],user_error),
558 bb_get(reset_test_runner_info,Info),
559 format(user_error,'*** Tests run: ~w, skipped: ~w, failed: ~w (for ~w) ***~n*** Failed tests:~n',[Nr,NrSkips,NrFails,Info]),
560 test_failed(X), lookup_test_description(X,Desc),
561 format(user_error,'~w ~w~n',[X,Desc]),
562 fail.
563 print_failed_tests :- nl(user_error),
564 (user_interrupt_signal_received -> format(user_error,'Tests were interrupted by CTRL-C (user_interrupt)~n',[])
565 ; true),
566 reset_terminal_colour(user_error).
567
568 lookup_test_description(Id,Desc) :- cli_testcase(Id,_,_,_,Desc).
569
570 :- dynamic user_interrupt_signal_received/0.
571 run_list(List) :- run_list(List,allow_skipping).
572 run_list(List,AllowSkipping) :-
573 init_test_runner,
574 retractall(user_interrupt_signal_received),
575 length(List,Len),
576 run_single_testcase_list_aux(List,Len,AllowSkipping).
577 run_single_testcase_list_aux([],_,_) :- !.
578 run_single_testcase_list_aux(List,_Len,allow_skipping) :- user_interrupt_signal_received,!,
579 length(List,RestLen),
580 format('Skipping ~w remaining tests~n',[RestLen]),
581 maplist(assert_test_skipped,List).
582 run_single_testcase_list_aux([TC|Tail],Len,AllowSkipping) :-
583 print_progress_stats(Len),
584 run_single_testcase(TC,AllowSkipping),
585 run_single_testcase_list_aux(Tail,Len,AllowSkipping).
586 assert_test_skipped(Id) :- assertz(test_skipped(Id)).
587
588 print_progress_stats(All) :- number_of_tests_run(Nr), Nr>0,!,
589 findall(Y,test_failed(Y),Fails), length(Fails,NrFails),
590 (last_test_failed(Failed) -> ajoin(['(e.g. ', Failed, ')'],FailInfo) ; FailInfo = ''),
591 findall(Y,test_skipped(Y),Skips), length(Skips,NrSkips),
592 bb_get(reset_test_runner_wtime,WStart),
593 statistics(walltime,[WNow,_]), Delta is round((WNow - WStart) / 1000),
594 bb_get(reset_test_runner_info,Info),
595 format_progress_nl('Progress: ~w/~w tests run, ~w skipped, ~w failed ~w (running since ~w sec for ~w)',[Nr,All,NrSkips,NrFails,FailInfo,Delta,Info]).
596 print_progress_stats(_).
597
598 cache :- add_additional_arguments(['-cache','/Users/leuschel/svn_root/NewProB/examples/cache/']).
599 v :- add_additional_arguments(['-v']). % verbose
600 vv :- add_additional_arguments(['-vv']). % very_verbose
601
602 :- volatile additional_arguments/1.
603 :- dynamic additional_arguments/1.
604 % add additional cli arguments when running tests:
605 add_additional_arguments(List) :-
606 (retract(additional_arguments(Old)) -> true ; Old=[]),
607 append(Old,List,New),
608 assertz(additional_arguments(New)).
609
610 reset_additional_arguments :- retractall(additional_arguments(_)).
611
612 % auto complete a preference name and print error if no match found
613 get_preference_name(Prefix,Name) :- auto_complete_preference(Prefix,Name),!.
614 get_preference_name(Prefix,_) :-
615 format_warning_nl('No matching preference found for: ~w',[Prefix]),fail.
616
617 :- use_module(probsrc(preferences),[eclipse_preference/2]).
618 auto_complete_preference(Prefix,Name) :-
619 atom_codes(Prefix,PC),
620 eclipse_preference(EP,Name),
621 (atom_codes(EP,EPC) ; atom_codes(Name,EPC)),
622 append(PC,_,EPC).
623
624 % add additional preference when running tests:
625 add_additional_preference(PREF,PREFVAL) :-
626 (retract(additional_arguments(Old0)) -> remove_matching_pref(Old0,PREF,Old) ; Old=[]),
627 New = ['-p',PREF,PREFVAL|Old],
628 format('New additional arguments: ~w~n',[New]),
629 assertz(additional_arguments(New)).
630
631 % remove all preferences conflicting with PREF
632 remove_matching_pref([],_PREF,[]).
633 remove_matching_pref(['-p',P,OLD|T],PREF,Res) :- !,
634 (P=PREF -> Res=T ; Res = ['-p',P,OLD|RT], remove_matching_pref(T,PREF,RT)).
635 remove_matching_pref([H|T],PREF,[H|RT]) :- remove_matching_pref(T,PREF,RT).
636
637 % remove all preferencs conflicting with other list of prefs
638 remove_matching_prefs([],P,P).
639 remove_matching_prefs(['-cache',_File|T],InPrefs,Res) :- !,
640 remove_matching_prefs(T,InPrefs,Res).
641 remove_matching_prefs(['-p',PREF,_|T],InPrefs,Res) :-
642 remove_matching_pref(InPrefs,PREF,In2),
643 remove_matching_prefs(T,In2,Res).
644 remove_matching_prefs([_|T],InPrefs,Res) :-
645 remove_matching_prefs(T,InPrefs,Res).
646
647 :- use_module(probsrc(pathes_lib), [unavailable_extension/2]).
648 unavailable_extension_for_test(Id,TestCategories,Ext,Reason) :-
649 ? test_requires_extension(Id,TestCategories,Ext),
650 ? unavailable_extension(Ext,Reason).
651
652 :- dynamic skip_all_tests/0.
653
654 skip_test(_, _, _, ReasonMsg, ReasonTerm) :-
655 skip_all_tests,
656 !,
657 ReasonMsg = 'skipping all tests',
658 ReasonTerm = skip_all_tests.
659 skip_test(_Id, _TestCategories, TestConfigurationInfos, ReasonMsg, ReasonTerm) :-
660 member(skip,TestConfigurationInfos),
661 !,
662 ReasonMsg = 'test marked as skipped',
663 ReasonTerm = skip.
664 skip_test(_Id, _TestCategories, TestConfigurationInfos, ReasonMsg, ReasonTerm) :-
665 ? member(conditional_skip(Callable), TestConfigurationInfos),
666 % Evaluate the condition in the context of the testcases module,
667 % where it was defined, so that imports are visible to the condition.
668 % We can't use a meta_predicate declaration here,
669 % because the goal is nested inside a term.
670 call(testcases:Callable),
671 !,
672 ReasonMsg = 'skip condition is true',
673 ReasonTerm = conditional_skip(Callable).
674 skip_test(_Id, TestCategories, _TestConfigurationInfos, ReasonMsg, ReasonTerm) :-
675 ? member(private, TestCategories),
676 \+ absolute_file_name(prob_examples(examples), _, [access(exist), file_type(directory), file_errors(fail)]),
677 !,
678 ReasonMsg = 'test requires non-public examples which are not available',
679 ReasonTerm = private.
680 skip_test(_Id, TestCategories, _TestConfigurationInfos, ReasonMsg, ReasonTerm) :-
681 ? member(private_source_not_available, TestCategories),
682 \+ directory_exists('../private_examples'),
683 !,
684 ReasonMsg = 'test requires private examples which are not available',
685 ReasonTerm = private_source_not_available.
686 skip_test(_Id, _TestCategories, TestConfigurationInfos, ReasonMsg, ReasonTerm) :-
687 current_prolog_flag(dialect, swi),
688 % TODO Handle swi_expected_failure differently.
689 % Ideally, tests that are expected to fail on SWI should not be skipped,
690 % but instead should be run normally with any failures ignored.
691 % This would allow detecting when tests unexpectedly succeed
692 % (i. e. have been fixed, but not unmarked as expected failure yet).
693 member(swi_expected_failure, TestConfigurationInfos),
694 !,
695 ReasonMsg = 'test expected to fail on SWI-Prolog',
696 ReasonTerm = swi_expected_failure.
697 skip_test(_Id, TestCategories, _TestConfigurationInfos, ReasonMsg, ReasonTerm) :-
698 ? group_cannot_be_checked_on_ci_server(Category),
699 member(Category, TestCategories),
700 !,
701 ReasonMsg = 'category cannot be checked on CI',
702 ReasonTerm = Category.
703 skip_test(Id, TestCategories, _TestConfigurationInfos, ReasonMsg, ReasonTerm) :-
704 ? unavailable_extension_for_test(Id,TestCategories,Ext,Reason),
705 !,
706 ajoin(['test requires an unavailable extension (',Reason,')'],ReasonMsg),
707 ReasonTerm = Ext.
708
709
710 % RUNNING SINGLE TESTCASE:
711 % ------------------------
712
713 :- dynamic previous_test_run/1.
714 previous_test_run(none).
715
716 :- use_module(library(timeout), [time_out/3]).
717
718 run_single_testcase(testcase(Id,TestCategories,Infos,Arguments,Comment),AllowSkipping) :-
719 skip_test(Id,TestCategories,Infos,ReasonMsg,ReasonTerm),
720 (AllowSkipping = allow_skipping -> true
721 ; % Skipping disabled - print message, then continue to next clause to run the test anyway.
722 format_progress_nl('Running test that would normally be skipped - ~w: ~q', [ReasonMsg,ReasonTerm]),
723 fail),
724 !,
725 full_flush,
726 format_with_colour_nl(user_output,[blue,bold],'Skipping test ~w (~w) because ~w: ~q', [Id,Comment,ReasonMsg,ReasonTerm]),
727 print_junit_skip(Arguments),
728 assertz(test_skipped(Id)),
729 full_flush.
730 run_single_testcase(testcase(Id,_TestCategories,_Infos,Arguments,Comment),AllowSkipping) :-
731 test_requires_previous_test(Id,ReqPreviousId),
732 previous_test_run(PreviousId),
733 PreviousId \= ReqPreviousId,!,
734 format_warning_nl('~n*** Test id ~w requires test ~w to be run just before, but previous test is ~w',
735 [Id,ReqPreviousId,PreviousId]),
736 (AllowSkipping = allow_skipping -> true
737 ; format_progress_nl('Running test that would normally be skipped', []),fail),
738 !,
739 full_flush,
740 format_with_colour_nl(user_output,[blue,bold],'Skipping test ~w (~w)', [Id,Comment]),
741 print_junit_skip(Arguments),
742 assertz(test_skipped(Id)),
743 full_flush.
744 run_single_testcase(testcase(Id,_TestCategories,_Infos,Arguments,Comment),_) :-
745 full_flush,
746 format_progress_nl('Running test ~w ~n ~w',[Id,Comment]),
747 retractall(previous_test_run(_)), assert(previous_test_run(Id)),
748 (debug_mode(off) -> true ; print('testcase: probcli '), print_args(Arguments),nl),
749 clear_diff_output(Id),
750 clear_logxml_output(Id),
751 prob_junit_args(JUnitArgs),
752 maplist(patch_prob_examples_loc,Arguments,Arguments0), % update path to prob_examples if necessary
753 append(Arguments0, JUnitArgs, Arguments1),
754 (additional_arguments(ExtraArgs)
755 -> remove_matching_prefs(ExtraArgs,Arguments1,RemArguments1), % remove conflicting arguments now overriden
756 append(ExtraArgs,RemArguments1,Arguments2)
757 ; Arguments1=Arguments2),
758 ? (tests_multiply_timeout(Factor) -> modify_timeout(Factor,Arguments2,Arguments3) ; Arguments3 = Arguments2),
759 (no_strict_running, select('-strict',Arguments3,Arguments4) -> true ; Arguments4=Arguments3),
760 (silent_running -> true ; print('executing: probcli '), print_args(Arguments4),nl),
761 full_flush,
762 test_started(Id),
763 time_out(catch(prob_cli:run_probcli(Arguments4,[test_runner]), Exception, true),
764 2147483646,TO_Result), !,
765 test_finished(Id,Walltime),
766 (TO_Result \= success % time_out occured, possibly due to throw(time_out);
767 -> Exception = TO_Result % et Exception to time_out
768 ; true),
769 (test_exception_is_success(Exception)
770 -> check_diff_output(Id),
771 check_logxml(Id)
772 ; format_warning_nl('Exception in test ~w: ~w',[Id,Exception]),
773 handle_test_exception(Exception),
774 print_test_failed(Id,Exception)
775 ),
776 (prolog_error_occurred ->
777 print_test_failed(Id,'Error(s) from Prolog during test! See console log for details. Aborting test run.'),
778 halt1
779 ; true),
780 !,
781 (test_failed(Id) % asserted by check_diff_output/check_logxml/print_test_failed
782 -> true % messages already printed above
783 ; format_with_colour_nl(user_output,[green],'Test ~w completed successfully (in ~w ms)~n',[Id,Walltime])
784 ),
785 safe_reset_cli(Id),
786 full_flush.
787
788 test_exception_is_success(Exception) :- var(Exception), !. % No exception was actually thrown
789 test_exception_is_success(Exception) :- Exception == halt(0). % can be thrown by typechecker_test
790
791 handle_test_exception(Exception) :-
792 ( Exception = error(_,_) -> Type = 'Error'
793 ; Exception = enumeration_warning(_,_,_,_,_) -> Type = 'Enumeration exception'
794 ; Exception = solver_and_provers_too_weak -> Type = 'Solver exception'
795 ; fail
796 ),
797 !,
798 (halt1_allowed
799 -> format_warning_nl('~w during test execution: ~w',[Type,Exception]),
800 halt1
801 ; true).
802 handle_test_exception(halt(1)) :- !.
803 handle_test_exception(parse_errors(_)) :- !.
804 handle_test_exception(time_out) :- !.
805 handle_test_exception(user_interrupt_signal) :- !,
806 assertz(user_interrupt_signal_received),
807 format_warning_nl('CTRL-C received, aborting tests',[]).
808 handle_test_exception(Exception) :-
809 format_warning_nl('Exception not caught in test_runner: ~w',[Exception]),
810 halt1.
811
812 safe_reset_cli(Id) :-
813 catch(prob_cli:reset_cli, % when bundles/extensions are missing we can get exceptions here
814 Exception,
815 (halt1_allowed
816 -> format_warning_nl('Exception while resetting probcli: ~w',[Exception]),
817 halt1
818 ; print_test_failed(Id,Exception)
819 )).
820
821 :- dynamic test_took_aux/2.
822 :- dynamic last_testcase_run/1, number_of_tests_run/1.
823 number_of_tests_run(0).
824 reset_nr_of_tests :- retractall(number_of_tests_run(_)), assertz(number_of_tests_run(0)).
825
826 :- use_module(library(system),[now/1, datime/2]).
827 :- dynamic performance_session_running/1, performance_session_stats/4.
828
829 performance_session_start :-
830 now(When),
831 datime(When,datime(Year,Month,Day,Hour,Min,Sec)),
832 format('~nStarting Codespeed Performance Monitoring session ~w:~w:~w:~w:~w:~w~n',[Year,Month,Day,Hour,Min,Sec]),
833 retractall(performance_session_running(_)),
834 assertz(performance_session_running(When)).
835
836 :- use_module(probsrc(parsercall),[get_parser_version/1]).
837 :- use_module(probsrc(version), [version_str/1, revision/1, lastchangeddate/1,
838 format_prolog_version/1, format_prob_version/1]).
839 performance_session_end(FilePrefix) :-
840 performance_session_running(When),
841 datime(When,datime(Year,Month,Day,Hour,Min,Sec)),
842 %tools:ajoin([FilePrefix,':',Year,Month,Day,Hour,Min,Sec],FileName),
843 format('~nFinishing Codespeed session ~w:~w:~w:~w:~w:~w~n -> File : ~w~n',[Year,Month,Day,Hour,Min,Sec,FilePrefix]),
844 open(FilePrefix,append,S),
845 format(S,'~n/* Codespeed session ~w:~w:~w:~w:~w:~w */~n',[Year,Month,Day,Hour,Min,Sec]),
846 version_str(Vers), portray_clause(S, session_prob_version(When,Vers)),
847 revision(Rev), portray_clause(S, session_prob_revision(When,Rev)),
848 lastchangeddate(DD), portray_clause(S, session_prob_lastchangeddate(When,DD)),
849 get_parser_version(PV), portray_clause(S, session_prob_parser_version(When,PV)),
850 current_prolog_flag(version, PrologVString),
851 portray_clause(S, session_prolog_version_string(When,PrologVString)),
852 current_prolog_flag(version_data, PrologVData),
853 portray_clause(S, session_prolog_version_data(When,PrologVData)),
854 current_prolog_flag(host_type, HostType),
855 portray_clause(S, session_prolog_host_type(When,HostType)),
856 write_perf_data(When,S).
857
858 write_perf_data(When,S) :- additional_arguments(New),
859 portray_clause(S, stored_additional_arguments(When,New)),
860 fail.
861 write_perf_data(When,S) :- performance_session_stats(When,Id,Time,WTime),
862 portray_clause(S, stored_performance_test_stats(When,Id,Time,WTime)),
863 fail.
864 write_perf_data(_When,S) :- nl(S), nl(S), close(S).
865
866
867
868 test_started(Id) :-
869 retractall(last_testcase_run(_)), assertz(last_testcase_run(Id)),
870 retractall(test_took_aux(_,_)),
871 statistics(runtime,[Start,_]),
872 statistics(walltime,[WStart,_]),
873 bb_put(test_started,Start),
874 bb_put(test_started_wtime,WStart),
875 bb_put(test_target_coverage,0). % a special value which can be increased in ProB's source code
876 % useful to measure the number of tests that cover a new feature
877
878 :- public inc_test_target_coverage/0.
879 % call this from prob_prolog if some code point you wish to test is covered
880 % using the stats repl command you can then see how many tests have covered this code point
881 inc_test_target_coverage :-
882 bb_get(test_target_coverage,X),
883 X1 is X+1,
884 bb_put(test_target_coverage,X1).
885
886 :- dynamic test_stats/6.
887 test_finished(Id,WTime) :-
888 statistics(runtime,[End,_]),
889 statistics(walltime,[WEnd,_]),
890 bb_get(test_started,Start),
891 bb_get(test_started_wtime,WStart),
892 bb_get(test_target_coverage,Covered),
893 Time is End - Start, WTime is WEnd- WStart,
894 retractall(test_took_aux(_,_)),
895 assertz(test_took_aux(Time,WTime)),
896 (retract(number_of_tests_run(Nr)) -> N1 is Nr+1 ; N1=1),
897 assertz(number_of_tests_run(N1)),
898 (retract(test_stats(Id,PrevTime,PrevWTime,_,_,_))
899 -> assertz(test_stats(Id,Time,WTime,PrevTime,PrevWTime,Covered))
900 ; assertz(test_stats(Id,Time,WTime,-1,-1,Covered))
901 ),
902 (performance_session_running(When)
903 -> assertz(performance_session_stats(When,Id,Time,WTime))
904 ; true).
905
906 print_delta_stats :- print('Comparing walltimes with previous test run: '),nl,
907 findall(delta(DeltaPerc,DeltaWTime,Id),test_delta_stat(Id,DeltaPerc,DeltaWTime),L),
908 (L=[] -> print('No previous run information available'),nl
909 ; print(' ID | % (delta absolute) | walltime (runtime)~n'),nl,
910 sort(L,SL),
911 maplist(print_delta,SL)).
912 test_delta_stat(Id,DeltaPerc,DeltaWTime) :-
913 test_stats(Id,_RTime,WTime,_PrevRTime,PrevWTime,_),
914 PrevWTime>0,
915 DeltaWTime is WTime - PrevWTime,
916 DeltaPerc is (100*DeltaWTime) / PrevWTime.
917 print_delta(delta(DeltaPerc,DeltaWTime,Id)) :-
918 test_stats(Id,RTime,WTime,_PrevRTime,PrevWTime,_Cov),
919 format(' ~w | ~2f % (~w ms) | ~w ms (~w ms runtime) [~w walltime ms previously]~n',
920 [Id,DeltaPerc,DeltaWTime,WTime,RTime,PrevWTime]).
921
922 :- use_module(probsrc(tools),[print_memory_used_wo_gc/0]).
923 print_current_stats :- print_current_stats(user_output,' | ').
924 print_current_stats(Stream,Sep) :-
925 print_memory_used_wo_gc,nl,
926 bb_put(test_target_coverage_nr,0),
927 bb_put(test_target_coverage_count,0),
928 bb_put(test_counter_nr,0),
929 format(Stream,' ID~wOK~wWALLTIME (ms)~wRUNTIME (ms)~wCOV~wDESCRIPTION~n',[Sep,Sep,Sep,Sep,Sep]),
930 test_stats(Id,RTime,WTime,_PrevRTime,_PrevWTime,NrTargetCoverage),
931 cli_testcase(Id,_Cat,_,_Args,Desc),
932 (test_failed(Id) -> OK = '*FAILED*' ; OK = ' OK '),
933 format(Stream,' ~w~w~w~w~w~w~w~w~w~w~w~n',
934 [Id,Sep,OK,Sep,WTime,Sep,RTime,Sep,NrTargetCoverage,Sep,Desc]),
935 bb_get(test_counter_nr,Nr), Nr1 is Nr+1, bb_put(test_counter_nr,Nr1),
936 (NrTargetCoverage>0
937 -> bb_get(test_target_coverage_nr,TN), TN1 is TN+1, bb_put(test_target_coverage_nr,TN1),
938 bb_get(test_target_coverage_count,NC), NC1 is NC+NrTargetCoverage,
939 bb_put(test_target_coverage_count,NC1)
940 ),
941 fail.
942 print_current_stats(_,_) :-
943 bb_get(test_counter_nr,NrT),
944 format('Number of tests: ~w~n',[NrT]),
945 (bb_get(test_target_coverage_nr,Nr), Nr>0 ->
946 bb_get(test_target_coverage_count,NrC),
947 Perc is (100.0 * Nr) / NrT,
948 format('Number of tests reaching test source code target: ~w (~2f %, total hits: ~w)~n',[Nr, Perc, NrC])
949 ; true).
950
951 test_took(Time,WTime) :- test_took_aux(Time,WTime), !.
952 test_took(0,0) :-
953 format_warning_nl('test_took/2 called before test_finished/2, this should not happen!',[]).
954
955 print_junit_skip(Arguments) :-
956 prob_junit_dir(Dir)
957 -> set_junit_dir(Dir),
958 create_and_print_junit_result(['Integration Tests'],Arguments,0,skip)
959 ; true.
960
961 % if the test expects a time_out error, the timeout is not expanded
962 % otherwise, timeout is increased to allow coverage analysis / junit / etc to finish
963 :- use_module(probsrc(tools_meta), [no_time_out_value/1]).
964 multiply_and_truncate_timeout(OrigTimeout, Factor, NewTimeout) :-
965 no_time_out_value(NoTimeout),
966 % Make sure that the new timeout never exceeds the special "no timeout" value,
967 % otherwise ProB prints lots of warnings about the timeout being too high.
968 (Factor = disable_time_out -> NewTimeout = NoTimeout
969 ; NewTimeout is min(round(Factor * OrigTimeout), NoTimeout)). % Factor could be float
970
971 modify_timeout(_,OldOptions,New) :-
972 append(_,['-expcterr','time_out'|_],OldOptions), !, New=OldOptions. % we expect a time_out
973 modify_timeout(Factor,[],['-p','TIME_OUT',NVal]) :-
974 % timeout was not set at all - set it to Factor*Default
975 % Note: there is a potential problem when the time_out is set inside the machine and not in the test !! TO DO: fix
976 preferences:preference_default_value(time_out,DEFAULT),
977 multiply_and_truncate_timeout(DEFAULT, Factor, NVal).
978 modify_timeout(Factor,[GTC,OLD|T],[GTC,NewT|MT]) :- is_global_time_out_cmd(GTC),!,
979 tools:arg_is_number(OLD,OLDT),
980 multiply_and_truncate_timeout(OLDT,Factor, NewT),
981 ? modify_timeout(Factor,T,MT).
982 modify_timeout(Factor,['-p','TIME_OUT',OLD|T],['-p','TIME_OUT',NewT|T]) :-
983 tools:arg_is_number(OLD,OLDT), !,
984 multiply_and_truncate_timeout(OLDT, Factor, NewT). % TODO: we currently assume global_time_out appears before
985 ?modify_timeout(Factor,[H|T],[H|MT]) :- modify_timeout(Factor,T,MT).
986
987 is_global_time_out_cmd('-global_time_out').
988 is_global_time_out_cmd('--global_time_out').
989 is_global_time_out_cmd('-time_out'). % old version
990
991 full_flush :- flush_output(user_output), flush_output(user_error).
992
993 print_args(List) :- print_args(List,15,15).
994 print_args([],_,_).
995 print_args([H|T],Nr,MaxPerLine) :- print(H),
996 (Nr<1 -> write(' \\'),nl, N1=MaxPerLine ; N1 is Nr-1),
997 write(' '), print_args(T,N1,MaxPerLine).
998
999 print_test_failed(Id,Msg) :-
1000 print_test_failed(Id,Msg,'').
1001 print_test_failed(Id,Msg1,Msg2) :-
1002 (Msg1 = user_interrupt_signal -> assertz(user_interrupt_signal_received) ; true),
1003 test_took(RunTime,WallTime),
1004 cli_testcase(Id,Categories,_Infos,Arguments,Comment),
1005 Categories = [FirstCat|_], !,
1006 ErrorMessage = ['Test with Id',Id,'failed.','Test Categories: ',Categories,'Test Arguments: ',Arguments,'Test Comment: ',Comment,'Error Messages in Test Runner: ',Msg1,Msg2,'Content of Error Manager: '],
1007 (get_all_errors(AllErrors) -> true ; AllErrors = []),
1008 append(ErrorMessage,AllErrors,FullErrorMessage),
1009 create_and_print_junit_result(['Integration Tests',FirstCat],Id,RunTime,error(FullErrorMessage)),
1010 assert_test_failed(Id),
1011 start_terminal_colour(red,user_error),
1012 format(user_error,'*** Test ~w FAILED (after ~w ms runtime, ~w ms walltime): ~w~w~n',
1013 [Id,RunTime,WallTime,Msg1,Msg2]),
1014 write('***'),print_memory_used_wo_gc,nl,
1015 reset_terminal_colour(user_error).
1016
1017 assert_test_failed(Id) :-
1018 assertz(test_failed(Id)),
1019 retractall(last_test_failed(_)),
1020 assertz(last_test_failed(Id)).
1021
1022 diff_failed(Id,F1,F2,DiffOutputText,CmpOutputText) :-
1023 test_took(Time,_),
1024 atom_codes(DiffOutputAtom,DiffOutputText),
1025 atom_codes(CmpOutputAtom,CmpOutputText),
1026 ErrMsg = ['Diff for test with Id\n',Id,'\nfailed:\n','Output file\n',F1,'\ndoes not correspond to stored version\n',F2,
1027 '\nOutput of Diff:\n',DiffOutputAtom,
1028 '\nOutput of Cmp:\n',CmpOutputAtom],
1029 create_and_print_junit_result(['Diff Checking'],Id,Time,error(ErrMsg)),
1030 assert_test_failed(Id),
1031 assertz(test_diff_failed(Id,F1,F2)),
1032 start_terminal_colour(red,user_error),
1033 format(user_error,'*** Test ~w FAILED: Diff failed:~nOutput file ~w~ndoes not correspond to stored version~n~w~n', [Id,F1,F2]),
1034 format(user_error,'Diff:~n~s~n',[DiffOutputText]),
1035 format(user_error,'Cmp:~n~s~n',[CmpOutputText]),
1036 reset_terminal_colour(user_error).
1037
1038 :- use_module(probsrc(tools_commands),[diff_files_with_editor/2]).
1039 diff_in_editor :- findall(I,test_diff_failed(I,_,_),LI), sort(LI,SI),
1040 format('Opening failed diff files in editor: ~w~n',[SI]),
1041 test_diff_failed(Id,F1,F2),
1042 format('Test ~w~n~w ~w~n',[Id,F1,F2]),
1043 diff_files_with_editor(F1,F2),
1044 fail.
1045 diff_in_editor.
1046
1047
1048 clear_diff_output(Id) :- % clear all files that should be generated
1049 ? get_testcase_diff_check_output(Id,GeneratedFile,_StoredReferenceFile),
1050 safe_file_exists(GeneratedFile),
1051 (get_testcase_do_not_delete(Id,GeneratedFile) -> formatsilent(user_output,'% Keeping: ~w~n',[GeneratedFile])
1052 ; formatsilent(user_output,'% Deleting: ~w~n',[GeneratedFile]),
1053 delete_file(GeneratedFile)
1054 ),fail.
1055 clear_diff_output(_).
1056
1057 check_diff_output(Id) :-
1058 findall(diff(Id,GeneratedFile,StoredReferenceFile),
1059 get_testcase_diff_check_output(Id,GeneratedFile,StoredReferenceFile),
1060 ListOfDiffsToCheck),
1061 maplist(check_diff_output2, ListOfDiffsToCheck).
1062
1063 check_diff_output2(diff(Id,GeneratedFile,StoredReferenceFile)) :-
1064 \+ safe_file_exists(GeneratedFile) -> print_test_failed(Id,'Output file does not exist:',GeneratedFile) ;
1065 \+ safe_file_exists(StoredReferenceFile) -> print_test_failed(Id,'Stored file does not exist:',StoredReferenceFile) ;
1066 diff(Id,GeneratedFile,StoredReferenceFile).
1067
1068 diff(Id,F1,F2) :-
1069 formatsilent(user_output,'% Checking: diff / cmp ~w ~w~n',[F1,F2]),
1070 get_command_path(diff,DiffPath),
1071 get_command_path(cmp,CmpPath),
1072 (system_call(DiffPath,['-b',F1,F2],DiffOutputText,_ErrTextDiff,ExitDiff) % use -q for quiet
1073 -> true
1074 ; DiffOutputText = "*** CALLING DIFF FAILED !", ExitDiff = fail
1075 ),
1076 formatsilent(user_output,'% Checking: cmp ~w ~w~n',[F1,F2]),
1077 (system_call(CmpPath,['-b',F1,F2],CmpOutputText,_ErrTextCmp,_ExitCmp)
1078 -> true
1079 ; CmpOutputText = "*** CALLING CMP FAILED !"
1080 ),
1081 (ExitDiff = exit(0)%, ExitCmp = exit(0)
1082 -> true
1083 ; diff_failed(Id,F1,F2,DiffOutputText,CmpOutputText)).
1084
1085
1086 % ----------------
1087 :- volatile logxml_file/1.
1088 % logxml file used automatically when started by test_runner
1089 :- dynamic logxml_file/1.
1090 clear_logxml_output(_Id) :- logxml_file(GeneratedFile),
1091 safe_file_exists(GeneratedFile),
1092 delete_file(GeneratedFile),
1093 fail.
1094 clear_logxml_output(_).
1095
1096 set_logxml_file(File) :- retractall(logxml_file(_)), assertz(logxml_file(File)),
1097 format('Adding -logxml ~w.~n',[File]),
1098 add_additional_arguments(['-logxml',File]).
1099
1100 :- use_module(probsrc(logger),[read_xml_log_file/2]).
1101 check_logxml(Id) :-
1102 logxml_file(File),!,
1103 xmllint(Id,File),
1104 check_logxml(Id,File).
1105 check_logxml(_).
1106
1107 xmllint(Id,File) :-
1108 (call_xmllint(File,ErrText,ExitLint)
1109 -> (ExitLint = exit(0) -> true
1110 ; print_test_failed(Id,'xmllint reported errors for file:',File),
1111 formatsilent(user_error,'% xmllint result~n~s~n',[ErrText])
1112 )
1113 ; print_test_failed(Id,'Calling xmllint failed for file:',File)
1114 ).
1115
1116 :- dynamic use_logxml_schema/0.
1117 set_use_logxml_schema :- (use_logxml_schema -> true ; assertz(use_logxml_schema)).
1118 call_xmllint(File,ErrText,ExitLint) :- use_logxml_schema,
1119 absolute_file_name(prob_home('doc/logxml_xsd.xml'),SchemaFile),
1120 file_exists(SchemaFile),!,
1121 get_command_path(xmllint,LintPath),
1122 format('Calling ~w with schema ~w for logxml file ~w~n',[LintPath,SchemaFile,File]),
1123 system_call(LintPath,['--schema', SchemaFile, File, '-noout'],_OutputText,ErrText,ExitLint).
1124 call_xmllint(File,ErrText,ExitLint) :-
1125 get_command_path(xmllint,LintPath),
1126 format('Calling ~w without schema for logxml file ~w~n',[LintPath,File]),
1127 system_call(LintPath,[File],_OutputText,ErrText,ExitLint).
1128
1129 check_logxml(Id,File) :-
1130 catch(read_xml_log_file(File,Infos), E,
1131 print_test_failed(Id,'Exception trying to read logxml file:',E)),
1132 !,
1133 format_progress_nl('Read logxml file ~w, contains ~w.',[File,Infos]),
1134 check_error_cound(Id,Infos).
1135 check_logxml(Id,File) :-
1136 print_test_failed(Id,'Logxml file could not be read:',File).
1137
1138 check_error_cound(Id,Infos) :-
1139 testcase_expects_errors(Id),!,
1140 (member(expected_errors/E,Infos),E>0 -> true ; print_test_failed(Id,'Logxml file does not report errors:',Infos)).
1141 check_error_cound(Id,Infos) :-
1142 (member(errors/0,Infos),member(expected_errors/0,Infos) -> true
1143 ; print_test_failed(Id,'Logxml file reports errors:',Infos)).
1144
1145 testcase_expects_errors(Id) :-
1146 cli_testcase(Id,_Cat,_Infos,Arguments,_Comment),
1147 member(A,Arguments), expect_error_arg(A).
1148
1149 expect_error_arg('-expcterr').
1150 expect_error_arg('-expecterr').
1151 expect_error_arg('-expect').
1152 expect_error_arg('-expcterrpos').
1153
1154 % ------------------
1155
1156 :- volatile repl_mode/0.
1157 :- dynamic repl_mode/0.
1158
1159 :- use_module(test_paths, [get_prob_examples_override/1, set_prob_examples_override/1]).
1160
1161 set_prob_examples_location(Dir) :-
1162 (atom(Dir) -> DirAtom = Dir ; atom_codes(DirAtom, Dir)),
1163 format('Setting location of prob_examples directory to: ~s~n',[DirAtom]),
1164 set_prob_examples_override(DirAtom).
1165
1166 % Prefixes of arguments that contain file paths,
1167 % which may need to be patched to an alternate prob_examples location.
1168 path_arg_prefix("#file ").
1169 path_arg_prefix(":cdclt #file ").
1170 path_arg_prefix(":cdclt-file ").
1171 path_arg_prefix(":cdclt-free #file ").
1172 path_arg_prefix(":cdclt-double-check #file ").
1173 path_arg_prefix(":cdclt-free-double-check #file ").
1174 path_arg_prefix(":prob-file ").
1175 path_arg_prefix(":z3 #file ").
1176 path_arg_prefix(":z3-double-check #file ").
1177 path_arg_prefix(":z3-free-double-check #file ").
1178 path_arg_prefix(":z3-file ").
1179 path_arg_prefix(":z3-free #file ").
1180 path_arg_prefix(":z3-free-file ").
1181 path_arg_prefix("").
1182
1183 % update path to prob_examples if necessary:
1184 patch_prob_examples_loc_0(NewLoc,Arg,PatchedArg) :-
1185 path_arg_prefix(Prefix),
1186 append(Prefix, ArgTail, Arg),
1187 append("../prob_examples", PathTail, ArgTail),
1188 !,
1189 append(NewLoc, PathTail, PatchedArgTail),
1190 append(Prefix, PatchedArgTail, PatchedArg).
1191
1192 patch_prob_examples_loc(Arg,PatchedArg) :-
1193 get_prob_examples_override(NewLocAtom),
1194 atom_codes(NewLocAtom, NewLoc),
1195 atom(Arg),
1196 atom_codes(Arg,ArgC),
1197 patch_prob_examples_loc_0(NewLoc,ArgC,PatchedArgC),
1198 !,
1199 atom_codes(PatchedArg,PatchedArgC),
1200 format('Patched ~w to ~w~n',[Arg,PatchedArg]).
1201 patch_prob_examples_loc(A,A).
1202
1203 get_testcase_do_not_delete(Id,PF) :-
1204 cli_testcase_do_not_delete(Id,F),
1205 patch_prob_examples_loc(F,PF).
1206
1207 get_testcase_diff_check_output(Id,PF1,PF2) :-
1208 ? cli_testcase_diff_check_output(Id,F1,F2),
1209 patch_prob_examples_loc(F1,PF1),
1210 patch_prob_examples_loc(F2,PF2).
1211
1212 :- use_module(extension('counter/counter'),[counter_init/0]).
1213 :- use_module(probsrc(prob_startup), [startup_prob/0]).
1214 init_test_runner :- startup_prob,counter_init.
1215 :- use_module(library(lists),[maplist/2]).
1216 % a minimal shell to execute tests:
1217 test_repl :-
1218 init_test_runner,
1219 format_prob_version(user_output),nl,
1220 format_prolog_version(user_output),nl,
1221 assertz(repl_mode),
1222 current_prolog_flag(argv,ArgV), treat_argv(ArgV),
1223 test_repl_loop,
1224 retractall(repl_mode).
1225
1226
1227
1228 treat_argv(['-prob-examples',Dir|T]) :- !, set_prob_examples_location(Dir),
1229 treat_argv(T).
1230 treat_argv(Args) :- maplist(eval_argv,Args).
1231
1232 % execute tests provided on the command-line:
1233 eval_argv(Cmd) :- format('ARGV ==> ~w~n',[Cmd]),
1234 atom_codes(Cmd,C), safe_number_codes(Nr,C), !, test_eval(Nr).
1235 eval_argv(Cmd) :- test_eval(Cmd),!.
1236
1237 test_repl_loop :- safe_read(T), test_eval(T), !, test_repl_loop.
1238 test_repl_loop.
1239
1240 safe_read(T) :-
1241 catch(
1242 (prompt(OldPrompt, 'TEST ==> '), call_cleanup(read(T), prompt(_, OldPrompt))),
1243 error(syntax_error(E),_),
1244 (format_warning_nl('*** Syntax error: ~w~n*** Type Prolog term followed by a dot(.) and enter.',[E]),
1245 safe_read(T))).
1246
1247 :- use_module(probsrc(translate),[print_open_stream_stats/0]).
1248 :- meta_predicate wall(0).
1249 wall(Call) :-
1250 statistics(walltime,[Start,_]),
1251 call(Call),
1252 statistics(walltime,[Stop,_]), WT is Stop-Start,
1253 format('Walltime: ~w ms~n',[WT]),
1254 print_memory_used_wo_gc,nl,
1255 (debug_mode(off) -> true ; print_open_stream_stats).
1256
1257 % -------------------------
1258
1259 :- use_module(library(file_systems)).
1260 :- use_module(probsrc(tools),[get_options/5]).
1261 % true for test_files
1262 test_file(Id,File,AbsFileName) :- cli_testcase(Id,_Cat,_Infos,Arguments,_Comment),
1263 get_options(Arguments,prob_cli:recognised_cli_option,_Options,Files,fail),
1264 member(File,Files),
1265 is_existing_file(File),
1266 absolute_file_name(File,AbsFileName).
1267
1268 is_existing_file(X) :- \+ number(X), atom(X),
1269 atom_codes(X,Codes),[BS] = "/", (member(BS,Codes) -> true),
1270 file_exists(X).
1271
1272 % obtain a list of all files used in tests
1273 all_files(Files) :- findall(F,test_file(_,_,F),A), sort(A,Files).
1274
1275 % a test file that can be loaded:
1276 valid_test_file(Id,File,AbsFileName,XT) :-
1277 test_file(Id,File,AbsFileName),
1278 cli_testcase(Id,_Cat,_Infos,Arguments,_Comment),
1279 \+ append(_,['-expcterr', load_main_file |_],Arguments),
1280 tools:get_filename_extension(File,XT).
1281 all_valid_files(Files,Mode) :-
1282 findall(F, (valid_test_file(_,_,F,XT),
1283 relevant_extension(XT,Mode)),
1284 A),
1285 sort(A,Files).
1286
1287 % traverse a directory and indicate which specification files are used in tests and which ones not
1288 traverse :- traverse('../prob_examples/public_examples/').
1289 traverse(SD) :- all_files(Files), absolute_file_name(SD,StartDir),
1290 format('Examining files in ~w~n + means file is used in some test~n~n',[StartDir]),
1291 traverse(StartDir,Files).
1292
1293 traverse(Dir,AllFiles) :- file_member_of_directory(Dir,_,FullFile),
1294 tools:get_filename_extension(FullFile,XT),
1295 (member(FullFile,AllFiles) -> format(' + ~w~n',[FullFile])
1296 ; relevant_extension(XT,_) -> format('--- ~w~n',[FullFile])),
1297 fail.
1298 traverse(Dir,AllFiles) :- directory_member_of_directory(Dir,_,SubDir),
1299 %format('~nSTART ~w~n',[SubDir]),
1300 traverse(SubDir,AllFiles),
1301 %format('~n END ~w~n',[SubDir]),
1302 fail.
1303 traverse(_,_).
1304
1305 relevant_extension('mch',b).
1306 relevant_extension('ref',b).
1307 relevant_extension('imp',b).
1308 relevant_extension('tla',tla).
1309 relevant_extension('fuzz',z).
1310 relevant_extension('tex',z).
1311 relevant_extension('csp',csp).
1312 relevant_extension('cspm',csp).
1313 relevant_extension('eventb',eventb).
1314
1315 % --------------------------
1316
1317 test_eval(quit) :- !,fail.
1318 test_eval(q) :- !,fail.
1319 test_eval(end_of_file) :- !,fail. % Ctrl-D
1320 test_eval(Cmd) :- test_eval1(Cmd),!.
1321 test_eval(Cmd) :-
1322 format_warning_nl('Error executing command: ~w',[Cmd]).
1323
1324 test_eval1(N) :- number(N),!, wall(run_id(N)).
1325 test_eval1(last) :- !, wall(run_last_test).
1326 test_eval1(N-M) :- number(N), number(M),!, wall(run_tests_by_id(N-M)).
1327 test_eval1('..'(N,M)) :- !, test_eval1(N-M).
1328 test_eval1(repeat(ID,M)) :- !, repeat_id(ID,M).
1329 test_eval1(r) :- !, run_random_tests(25).
1330 test_eval1(v) :- !,v.
1331 test_eval1(verbose) :- !,v.
1332 test_eval1(all_files) :- !, all_files(Files), length(Files,Len),
1333 format('~nFiles = ~n~w~n # Files = ~w~n',[Files,Len]).
1334 test_eval1(valid_files(Mode)) :- !, all_valid_files(Files,Mode), length(Files,Len),
1335 format('~nValid ~w Files = ~n~w~n # Files = ~w~n',[Mode,Files,Len]).
1336 test_eval1(files) :- !, traverse.
1337 test_eval1(files(Dir)) :- !, traverse(Dir).
1338 test_eval1(ex(Dir)) :- !, set_prob_examples_location(Dir).
1339 test_eval1(cache) :- !,print('Enabling cache'),nl,
1340 cache.
1341 test_eval1(debug) :- !,print('Enabling Prolog debugging mode (use -v or -vv for ProB debugging info)'),nl,
1342 debug,
1343 retractall(multiply_timeout(_)),
1344 assertz(multiply_timeout(10)).
1345 test_eval1(factor(X)) :- !,
1346 retractall(multiply_timeout(_)),
1347 format('Setting timeout factor to ~w~n',[X]),
1348 assertz(multiply_timeout(X)).
1349 test_eval1(disable_time_out) :- !, test_eval1(factor(disable_time_out)).
1350 test_eval1(timeout(X)) :- !,
1351 format('Adding -timeout ~w for model checking, disproving~nUse factor(X) to set TIME_OUT factor.~n',[X]),
1352 add_additional_arguments(['-timeout',X]).
1353 test_eval1(coverage) :- !,
1354 format('Adding -coverage to all commands.~n',[]),
1355 add_additional_arguments(['-coverage']).
1356 test_eval1(opreuse) :- !,
1357 format('Adding operation reuse to all commands.~n',[]),
1358 add_additional_arguments(['-p', 'OPERATION_REUSE',true]).
1359 test_eval1(opc) :- !,
1360 format('Adding operation reuse and compression to all commands.~n',[]),
1361 add_additional_arguments(['-p', 'COMPRESSION', 'TRUE', '-p', 'OPERATION_REUSE',true]).
1362 test_eval1(opcf) :- !,
1363 format('Adding operation reuse and compression to all commands.~n',[]),
1364 add_additional_arguments(['-p', 'COMPRESSION', 'TRUE', '-p', 'OPERATION_REUSE',full]).
1365 test_eval1(gc_trace) :- !,
1366 format('Adding -gc_trace to all commands.~n',[]),
1367 add_additional_arguments(['-gc_trace']).
1368 test_eval1(reset) :- !, reset_additional_arguments.
1369 test_eval1(logxml) :- !, File = './test_runner_logxml.xml',
1370 set_logxml_file(File).
1371 test_eval1(xsd) :- !, File = './test_runner_logxml.xml',
1372 set_logxml_file(File), set_use_logxml_schema.
1373 test_eval1(debug_off) :- !,print('Disabling Prolog debugging mode'),nl,
1374 nodebug,
1375 retractall(multiply_timeout(_)).
1376 test_eval1(fast) :- !,print('Enabling jvm_parser_fastrw'),nl,
1377 % TODO: only works at the very beginning; we need to be able to switch parser?
1378 add_additional_preference('jvm_parser_fastrw','true'),
1379 add_additional_preference('jvm_parser_force_parsing','true').
1380 test_eval1(force) :- !,print('Setting jvm_parser_force_parsing'),nl,
1381 add_additional_preference('jvm_parser_force_parsing','true').
1382 test_eval1(clpfd) :- !,print('Enabling CLPFD'),nl,
1383 add_additional_preference('CLPFD','TRUE').
1384 test_eval1(clpfd_off) :- !,print('Disabling CLPFD'),nl,
1385 add_additional_preference('CLPFD','FALSE').
1386 test_eval1(smt) :- !,print('Enabling SMT'),nl,
1387 add_additional_preference('SMT','TRUE').
1388 test_eval1(smt_off) :- !,print('Disabling SMT'),nl,
1389 add_additional_preference('SMT','FALSE').
1390 test_eval1(chr) :- !,print('Enabling CHR'),nl,
1391 add_additional_preference('CHR','TRUE').
1392 test_eval1(chr_off) :- !,print('Disabling CHR'),nl,
1393 add_additional_preference('CHR','FALSE').
1394 test_eval1(cse_off) :- !,print('Disabling CSE'),nl,
1395 add_additional_preference('CSE','FALSE').
1396 test_eval1(cse) :- !,print('Enabling CSE'),nl,
1397 add_additional_preference('CSE','TRUE').
1398 test_eval1(cse_subst) :- !,print('Enabling CSE_SUBST'),nl,
1399 add_additional_preference('CSE','TRUE'),
1400 add_additional_preference('CSE_SUBST','TRUE').
1401 test_eval1(trace_info) :- !,print('Enabling TRACE_INFO'),nl,
1402 add_additional_preference('TRACE_INFO','TRUE').
1403 %
1404 test_eval1(p(PREF)) :- !,
1405 get_preference_name(PREF,PName),
1406 print('Enabling Preference '),print(PName),nl,
1407 add_additional_preference(PName,'true').
1408 test_eval1(p(PREF,VAL)) :- !,
1409 get_preference_name(PREF,PName),
1410 print('Setting Preference '),print(PName),nl,
1411 add_additional_preference(PName,VAL).
1412 test_eval1(random) :- !,print('Enabling RANDOMISE_ENUMERATION_ORDER'),nl,
1413 add_additional_preference('RANDOMISE_ENUMERATION_ORDER','TRUE').
1414 test_eval1(random_off) :- !,print('Enabling RANDOMISE_ENUMERATION_ORDER'),nl,
1415 add_additional_preference('RANDOMISE_ENUMERATION_ORDER','FALSE').
1416 test_eval1(safe) :- !,print('Setting PROB_SAFE_MODE'),nl,
1417 run_safely.
1418 test_eval1(sanity_check) :- !, sanity_check(false).
1419 test_eval1(sc) :- !, sanity_check(false).
1420 test_eval1(trace) :- !, print('Enabling TRACE_UPON_ERROR'),nl,
1421 add_additional_preference('TRACE_UPON_ERROR','TRUE').
1422 test_eval1(trace_off) :- !, print('Disabling TRACE_UPON_ERROR'),nl,
1423 add_additional_preference('TRACE_UPON_ERROR','FALSE').
1424 test_eval1(raise) :- !,print('Enabling STRICT_RAISE_ENUM_WARNINGS'),nl,
1425 add_additional_preference('STRICT_RAISE_ENUM_WARNINGS','TRUE').
1426 test_eval1(nopt) :- !,print('Disabling OPTIMIZE_AST'),nl,
1427 add_additional_preference('OPTIMIZE_AST','FALSE').
1428 test_eval1(vv) :- !,vv.
1429 test_eval1(version(X)) :- !, print_version(X). %cpp, java, full, lib
1430 test_eval1(version) :- !, print_version(full_verbose).
1431 test_eval1(silent) :- !, run_silently.
1432 test_eval1(nostrict) :- !, run_no_strict.
1433 test_eval1(no_strict) :- !, run_no_strict.
1434 test_eval1(strict) :- !, retractall(no_strict_running).
1435 test_eval1(skip) :- !, (retract(skip_all_tests) -> X=false ; assertz(skip_all_tests),X=true),
1436 format('Marking all tests as skipped: ~w~n',[X]).
1437 test_eval1(x) :- !,halt.
1438 test_eval1(reload) :- !,use_module(probsrc(test_runner)), use_module(probsrc(testcases)).
1439 :- if(predicate_property(make, _)).
1440 test_eval1(make) :- !, make.
1441 :- else.
1442 test_eval1(make) :- !,
1443 print('make/0 is only supported on SWI-Prolog - reloading just the testcases instead.'),nl,
1444 test_eval1(reload).
1445 :- endif.
1446 test_eval1(edit) :- last_testcase_run(Id),
1447 get_file_for_testcase(Id,File),!,
1448 edit_file(File).
1449 test_eval1(e) :- !, test_eval1(edit).
1450 test_eval1(diff) :- !, diff_in_editor.
1451 test_eval1(halt) :- !,halt.
1452 test_eval1(info) :- !, get_total_number_of_errors(X), format('~nTotal number of errors: ~w~n~n',[X]).
1453 test_eval1(cat) :- !, print('Categories: '),
1454 findall(Cat,
1455 (cli_testcase(_, TestCategories, _, _, _), member(Cat, TestCategories)), List),
1456 sort(List,SL), print(SL),nl,
1457 format('Type cat(Cat) or name of category to run it.~n',[]),
1458 format('Note: priv is an alias for private_source_not_available.~n',[]).
1459 test_eval1(all) :- !, wall(run_tests_all).
1460 test_eval1(cata) :- !, category_analysis.
1461 test_eval1(cat(Category)) :- !,
1462 wall(run_tests_by_category(Category,all)).
1463 test_eval1(priv) :- !, test_eval1(cat(private_source_not_available)).
1464 test_eval1(first(Category)) :- !,
1465 wall(run_tests_by_first_category(Category)).
1466 test_eval1(list(Category)) :- !,
1467 get_tests_for_categories([Category],TList),
1468 findall(Id,member(testcase(Id, _, _, _, _),TList),List),
1469 format('Tests for category: ~w~n',[List]).
1470 test_eval1(make(Categories)) :- !,
1471 wall(makefile_by_category(user_output,Categories)).
1472 test_eval1(make(File,Categories)) :- !,
1473 wall(makefile_by_category(File,Categories)).
1474 test_eval1(files(Category)) :- !, show_files(Category).
1475 test_eval1(uses(Command)) :- !, wall(run_tests_using_command(Command)).
1476 test_eval1(uses(Pref,Val)) :- !, wall(run_tests_using_preference(Pref,Val)).
1477 test_eval1(p) :- !, test_eval1(profile).
1478 test_eval1(ps) :- !, test_eval1(print_profile).
1479 test_eval1(pc) :- !, test_eval1(print_coverage).
1480 test_eval1(delta) :- !, print_delta_stats.
1481 test_eval1(stats) :- !, print_current_stats.
1482 test_eval1(statscsv) :- !, print_current_stats(user_output,',').
1483 test_eval1(start) :- !, performance_session_start.
1484 test_eval1(stop) :- !, performance_session_end('log/test_runner_performance_log.pl').
1485 test_eval1(codespeed) :- !,
1486 performance_session_start,
1487 test_eval1(cat(codespeed)),
1488 performance_session_end('log/test_runner_performance_codespeed_log.pl').
1489 test_eval1(prob_profile) :- !,
1490 cli_print_statistics(prob_profile),
1491 cli_print_statistics(disprover_profile).
1492 test_eval1(profile) :- !, print('PROFILING : '), %spy([avl:avl_size/2]),
1493 (current_prolog_flag(profiling,on)
1494 -> set_prolog_flag(profiling,off), print('OFF') ;
1495 set_prolog_flag(profiling,on), print('ON')),
1496 nl,print('USE ps to print_profile or pc to print_coverage info'),nl.
1497 test_eval1(profile_stats) :- !, test_eval1(print_profile).
1498 test_eval1(print_profile) :- !, nl,print('PROFILE INFORMATION:'), nl,
1499 catch(print_profile,
1500 error(existence_error(_,_),_),
1501 print('CAN ONLY BE USED WHEN RUNNING PROB FROM SOURCE')),
1502 nl, debug:timer_statistics.
1503 test_eval1(print_coverage) :- !, nl,print('COVERAGE INFORMATION:'), nl,
1504 (current_prolog_flag(source_info,on) -> true ; format_warning_nl('Only useful when current_prolog_flag(source_info,on)!',[])),
1505 catch(print_coverage,
1506 error(existence_error(_,_),_),
1507 print('CAN ONLY BE USED WHEN RUNNING PROB FROM SOURCE')),
1508 nl.
1509 test_eval1(profile_reset) :- !, nl,print('RESETTING PROFILE INFORMATION'), nl,
1510 catch(profile_reset,
1511 error(existence_error(_,_),_),
1512 print('CAN ONLY BE USED WHEN RUNNING PROB FROM SOURCE')),
1513 nl.
1514 test_eval1(perf) :- !, toggle_perfmessages.
1515 test_eval1(Category) :- valid_category(Category),!,
1516 wall(run_tests_by_category(Category,all)).
1517
1518 test_eval1(codespeed(Id)) :- !, codespeed_id(Id).
1519 test_eval1(module(Module)) :- !,
1520 prob_cli:run_probcli(['-selfcheck_module',Module],[test_runner]), safe_reset_cli(Module), full_flush.
1521 test_eval1(cs(Id)) :- !, codespeed_id(Id).
1522 test_eval1('-'(ProBCLICommand)) :- atom(ProBCLICommand),
1523 atom_concat('-',ProBCLICommand,Atom),
1524 (prob_cli:recognised_option(Atom,Call) -> true % from probcli.pl
1525 ; format('Unknown probcli command: -~w~n',[ProBCLICommand]),fail),
1526 !,
1527 format('Executing probcli command ~w~n',[Call]),
1528 call(prob_cli:Call).
1529 test_eval1([H|T]) :- number(H),!, wall(run_tests_by_id([H|T],_,no_skipping)).
1530 test_eval1([Category|T]) :- valid_category(Category),!,
1531 wall(run_tests_by_category([Category|T],all)).
1532 test_eval1(C) :-
1533 (C=help -> true ; format('*** Unknown command ~w~n',[C])),
1534 print(' Commands: Nr, Nr-Nr, last, q, x, v, vv, uses(Cmd), uses(Pref,Val),'),nl,
1535 print(' repeat(id,nr), timeout(ms),factor(f), e,edit,diff, r (for 25 random tests),'),nl,
1536 print(' cat, cat(Cats),make(Cats),make(File,Cats),files(Cat),'),nl,
1537 print(' profile, profile_stats, (to turn Prolog profiling on and print info)'),nl,
1538 print(' debug,debug_off, (to turn Prolog debug mode on or off)'),nl,
1539 print(' perf, reload, sc,'),nl,
1540 print(' -CMD, (for probcli commands like -profile)'),nl,
1541 print(' * for setting preferences:'),nl,
1542 print(' p(PREF), p(PREF,VAL),'),nl,
1543 print(' clpfd,clpfd_off, smt,smt_off, chr,chr_off, cse,cse_subst,cse_off,'),nl,
1544 print(' random,random_off, trace_info, nopt,'),nl,
1545 print(' cache, perf, (turn ProB caching or performance messages on)'),nl,
1546 print(' trace,trace_off, (set TRACE_UPON_ERROR preference)'),nl,
1547 print(' * statistics:'),nl,
1548 print(' delta, stats, info.'),nl.
1549
1550 safe_file_exists(F) :- atom(F), file_exists(F).
1551
1552 get_file_for_testcase(Id,File) :-
1553 cli_testcase(Id,_,_Infos,Arguments,_Comment),
1554 member(File,Arguments), safe_file_exists(File).
1555
1556 valid_category(Cat) :-
1557 cli_testcase(_Id, TestCategories, _Infos, _Arguments, _Comment),
1558 member(Cat, TestCategories).
1559
1560
1561 % ---------------------------
1562
1563 % run test using binary
1564 % binaries are registered in a file probcli_bak/codespeed_versions.pl
1565 % results for test ID are written to probcli_bak/codespeed/res_ID.csv
1566
1567 :- use_module(probsrc(tools), [ajoin/2,ajoin_with_sep/3]).
1568 codespeed_id(Ids) :- codespeed_id(Ids,[min_date(date(2020,1,1))]).
1569 codespeed_id([],_) :- !.
1570 codespeed_id([H|T],Options) :- !, codespeed_id(H,Options),!, codespeed_id(T,Options).
1571 codespeed_id(Cat,Options) :- atom(Cat),!,
1572 get_tests_for_categories([Cat],List),
1573 codespeed_id(List,Options).
1574 codespeed_id(testcase(Id, _, _, _, _),Options) :- !, codespeed_id(Id,Options).
1575 codespeed_id(Id,Options) :-
1576 use_module('probcli_bak/codespeed_versions.pl'), % contains probcli_binary
1577 cli_testcase(Id,_TestCategories,_TestInfos,Arguments,Comment),
1578 format('Benchmarking test ~w using probcli binaries ~w~nTest Description: ~w~n',[Id,Options,Comment]),
1579 maplist(convert_arg_to_atom,Arguments,Args2),
1580 findall(probcli_binary(V1,V2,V3,F,Path,Sics,Date),
1581 get_probcli_binary_info(Options,V1,V2,V3,F,Path,_Hash,Sics,Date),Binaries),
1582 Repeats=3,
1583 maplist(bench_probcli_binary_testcase(Id,Args2,Repeats),Binaries,Walltimes,Oks),
1584
1585 ajoin(['codespeed/res_',Id,'.csv'],FName),
1586 absolute_file_name(FName,AF,[relative_to(probcli_bak)]),
1587 format('Writing codespeed results for ~w to ~w~n',[Id,AF]),
1588 open(AF,write,Stream),
1589 format(Stream,'\"Test ~w\"~n',[Id]),
1590 format(Stream,'\"~w\"~n',[Comment]),
1591 ajoin_with_sep(Arguments,' ',ArgsStr),
1592 format(Stream,'Command:,\"probcli ~w\"~n~n',[ArgsStr]),
1593 format(Stream,'\"~w.~w.~w-~w\",~w,~w,~w,~w,~w,~w,\"~w\"~n',[v1,v2,v3,f,sics,date,avg,min,max,ok,walltimes]),
1594 maplist(print_codespeed_results(Stream,Repeats),Binaries,Walltimes,Oks),
1595 close(Stream),
1596 maplist(print_codespeed_results(user_output,Repeats),Binaries,Walltimes,Oks).
1597
1598 get_probcli_binary_info(Options,V1,V2,V3,F,Path,Hash,Sics,Date) :-
1599 probcli_binary(V1,V2,V3,F,Path,Hash,Sics,Date), % from codespeed_versions.pl
1600 (( member(min_date(D2),Options), D2 @> Date
1601 ; member(max_date(D3),Options), D3 @< Date
1602 ; member(min_version(V12,V22,V32),Options), v(V12,V22,V32) @> v(V1,V2,V3)
1603 )
1604 -> format('Excluding version ~w.~w.~w-~w ~w~n',[V1,V2,V3,F,Options]),
1605 fail
1606 ; % format('Including version ~w.~w.~w-~w ~w~n',[V1,V2,V3,F,Options]),
1607 true).
1608
1609
1610 %:- use_module(library(statistics),[min_max/3]).
1611 print_codespeed_results(Stream,Repeats,probcli_binary(V1,V2,V3,F,_Path,sicstus(S1,S2,S3),date(Y,M,D)),Walltimes,Ok) :-
1612 sumlist(Walltimes,Sum),
1613 Average is Sum / Repeats,
1614 min_member(Min,Walltimes),
1615 max_member(Max,Walltimes),
1616 ajoin([S1,'.',S2,'.',S3],Sics),
1617 ajoin([Y,'/',M,'/',D],Date),
1618 format(Stream,'\"~w.~w.~w-~w\",~w,~w,~w,~w,~w,~w,\"~w\"~n',[V1,V2,V3,F,Sics,Date,Average,Min,Max,Ok,Walltimes]).
1619
1620 %bench_probcli_binary_testcase(Id,_Args,_Repeats,probcli_binary(V1,V2,V3,F,Path,_,_),Walltimes,Ok) :-
1621 % format('~nDry run test ~w using version ~w.~w.~w-~w (~w)~n',[Id,V1,V2,V3,F,Path]),!, Ok=skipped, Walltimes=[0].
1622 bench_probcli_binary_testcase(Id,Args,Repeats,probcli_binary(V1,V2,V3,F,Path,_,_),Walltimes,Ok) :-
1623 format('~nRunning test ~w using version ~w.~w.~w-~w (~w)~n',[Id,V1,V2,V3,F,Path]),
1624 run_probcli_binary_testcase(Id,Path,Args,_WT,Ok), % run once for parser
1625 rep_bench(Repeats,Id,Path,Args,Walltimes).
1626
1627 rep_bench(0,_,_,_,[]).
1628 rep_bench(Nr,Id,Path,Args,[WT1|WTR]) :- Nr>0,
1629 run_probcli_binary_testcase(Id,Path,Args,WT1,_),
1630 N1 is Nr-1,
1631 rep_bench(N1,Id,Path,Args,WTR).
1632
1633 :- use_module(probsrc(system_call), [system_call/5]).
1634 run_probcli_binary_testcase(Id,Path,Arguments,WT,Ok) :-
1635 statistics(walltime,[Start,_]),
1636 % absolute_file_name('probcli_bak/',BakPath),
1637 % atom_concat(BakPath,Path,Cmd),
1638 absolute_file_name(Path,Cmd,[relative_to(probcli_bak)]),
1639 format(' Test ~w :: ~w ~w~n',[Id,Cmd,Arguments]),
1640 system_call(Cmd,Arguments,_OutputText,ErrText,Exit),
1641 statistics(walltime,[Stop,_]), WT is Stop-Start,
1642 format(' Walltime: ~w ms; ~w~n',[WT,Exit]),
1643 (Exit=exit(0), ErrText = [] -> Ok=true
1644 ; format_error_nl('STD-ERROR (~w):~n~s',[Exit,ErrText]), Ok=false
1645 ).
1646
1647 % convert for system_call/process_create which do not accept numbers:
1648 convert_arg_to_atom(Nr,Atom) :- number(Nr), number_codes(Nr,C),!,atom_codes(Atom,C).
1649 convert_arg_to_atom(A,A).
1650
1651
1652 % --------------------
1653
1654 category_analysis :-
1655 format('Analysing test categories:~n',[]),
1656 findall(Cat-Id,(cli_testcase(Id,Categories,_,_Args,_Comm1),member(Cat,Categories)),L),
1657 sort(L,SL),
1658 keyclumped(SL,Groups), % Groups = [ Cat1 - [TestNr1, ...], Cat2 - [...], ...]
1659 maplist(print_cat_group,Groups).
1660
1661 nr_of_files(Cat,Id,Nr,DistinctNr) :-
1662 findall(File,(cli_testcase(Id,Categories,_,Args,_Comm1),
1663 member(Cat,Categories),
1664 file_in_arguments(File,Args)),Files),
1665 length(Files,Nr),
1666 sort(Files,SFile),
1667 length(SFile,DistinctNr).
1668
1669 print_cat_group(Cat-Tests) :-
1670 Tests = [First|T],
1671 nr_of_files(Cat,_,NrFiles,Distinct),
1672 (T=[]
1673 -> format(' ~w : 1 test : [~w] : ~w files, ~w distinct~n',[Cat,First,NrFiles,Distinct])
1674 ; length(Tests,Len),
1675 last(T,Last),
1676 format(' ~w : ~w tests : [~w .. ~w] : ~w files, ~w distinct~n',[Cat,Len,First,Last,NrFiles,Distinct])
1677 ).
1678