How can I catch the output to the console in Prolog to verify it?

189 Views Asked by At

Suppose I have a hello_name.pl:

greeting (Name): -
   write ('hello'),
   write (Name),
   writeln ('!').

And I want to put in my plunit something like

catch_output (greeting ('Moncho'), ConsoleOutput),
  assertion ('hello Moncho!' =:= ConsoleOutput).
1

There are 1 best solutions below

0
Guy Coder On BEST ANSWER

If you are using

See: with_output_to/2

Note: with_output_to/2 is implemented using C in SWI-Prolog so is not portable as Prolog code.

?- with_output_to(string(Output),(write('hello'),write('Rusian'),write('!'))), 
   assertion( Output == "helloRusian!").

With corrections to your code and using SWI-Prolog unit tests

greeting(Name) :-
   write('hello'),
   write(Name),
   writeln('!').

:- begin_tests(your_tests).

test(001, Output == 'helloMoncho!\n') :-
    with_output_to(atom(Output), greeting('Moncho')).

:- end_tests(your_tests).