1## Copyright (C) 2005, 2006, 2007, 2008, 2009 Paul Kienzle
3## This file is part of Octave.
5## Octave is free software; you can redistribute it and/or modify it
6## under the terms of the GNU General Public License as published by
7## the Free Software Foundation; either version 3 of the License, or (at
8## your option) any later version.
10## Octave is distributed in the hope that it will be useful, but
11## WITHOUT ANY WARRANTY; without even the implied warranty of
12## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13## General Public License for more details.
15## You should have received a copy of the GNU General Public License
16## along with Octave; see the file COPYING. If not, see
17## <http://www.gnu.org/licenses/>.
20## @deftypefn {Function File} {} test @var{name}
21## @deftypefnx {Function File} {} test @var{name} quiet|normal|verbose
22## @deftypefnx {Function File} {} test ('@var{name}', 'quiet|normal|verbose', @var{fid})
23## @deftypefnx {Function File} {} test ([], 'explain', @var{fid})
24## @deftypefnx {Function File} {@var{success} =} test (@dots{})
25## @deftypefnx {Function File} {[@var{n}, @var{max}] =} test (@dots{})
26## @deftypefnx {Function File} {[@var{code}, @var{idx}] =} test ('@var{name}','grabdemo')
28## Perform tests from the first file in the loadpath matching @var{name}.
29## @code{test} can be called as a command or as a function. Called with
30## a single argument @var{name}, the tests are run interactively and stop
31## after the first error is encountered.
33## With a second argument the tests which are performed and the amount of
38## Don't report all the tests as they happen, just the errors.
41## Report all tests as they happen, but don't do tests which require
45## Do tests which require user interaction.
48## The argument @var{fid} can be used to allow batch processing. Errors
49## can be written to the already open file defined by @var{fid}, and
50## hopefully when Octave crashes this file will tell you what was happening
51## when it did. You can use @code{stdout} if you want to see the results as
52## they happen. You can also give a file name rather than an @var{fid}, in
53## which case the contents of the file will be replaced with the log from
56## Called with a single output argument @var{success}, @code{test} returns
57## true if all of the tests were successful. Called with two output arguments
58## @var{n} and @var{max}, the number of successful tests and the total number
59## of tests in the file @var{name} are returned.
61## If the second argument is the string 'grabdemo', the contents of the demo
62## blocks are extracted but not executed. Code for all code blocks is
63## concatenated and returned as @var{code} with @var{idx} being a vector of
64## positions of the ends of the demo blocks.
66## If the second argument is 'explain', then @var{name} is ignored and an
67## explanation of the line markers used is written to the file @var{fid}.
68## @seealso{error, assert, fail, demo, example}
71## FIXME: * Consider using keyword fail rather then error? This allows us
72## to make a functional form of error blocks, which means we
73## can include them in test sections which means that we can use
74## octave flow control for both kinds of tests.
76function [__ret1, __ret2, __ret3, __ret4] = test (__name, __flag, __fid)
77 ## Information from test will be introduced by "key".
78 persistent __signal_fail = "!!!!! ";
79 persistent __signal_empty = "????? ";
80 persistent __signal_block = " ***** ";
81 persistent __signal_file = ">>>>> ";
82 persistent __signal_skip = "----- ";
87 if (nargin < 2 || isempty (__flag))
93 if (nargin < 1 || nargin > 3
94 || (! ischar (__name) && ! isempty (__name)) || ! ischar (__flag))
97 if (isempty (__name) && (nargin != 3 || ! strcmp (__flag, "explain")))
100 __batch = (! isempty (__fid));
102 ## Decide if error messages should be collected.
106 __fid = fopen (__fid, "wt");
108 error ("could not open log file");
112 fprintf (__fid, "%sprocessing %s\n", __signal_file, __name);
118 if (strcmp (__flag, "normal"))
122 elseif (strcmp (__flag, "quiet"))
126 elseif (strcmp (__flag, "verbose"))
130 elseif (strcmp (__flag, "grabdemo"))
136 elseif (strcmp (__flag, "explain"))
137 fprintf (__fid, "# %s new test file\n", __signal_file);
138 fprintf (__fid, "# %s no tests in file\n", __signal_empty);
139 fprintf (__fid, "# %s test had an unexpected result\n", __signal_fail);
140 fprintf (__fid, "# %s code for the test\n", __signal_block);
141 fprintf (__fid, "# Search for the unexpected results in the file\n");
142 fprintf (__fid, "# then page back to find the file name which caused it.\n");
143 fprintf (__fid, "# The result may be an unexpected failure (in which\n");
144 fprintf (__fid, "# case an error will be reported) or an unexpected\n");
145 fprintf (__fid, "# success (in which case no error will be reported).\n");
152 error ("test unknown flag '%s'", __flag);
155 ## Locate the file to test.
156 __file = file_in_loadpath (__name, "all");
157 if (isempty (__file))
158 __file = file_in_loadpath (cstrcat (__name, ".m"), "all");
160 if (isempty (__file))
161 __file = file_in_loadpath (cstrcat (__name, ".cc"), "all");
164 ## If repeats, return first in path.
165 if (isempty (__file))
171 if (isempty (__file))
176 fprintf (__fid, "%s%s does not exist in path\n", __signal_empty, __name);
188 ## Grab the test code from the file.
189 __body = __extract_test_code (__file);
191 if (isempty (__body))
196 fprintf (__fid, "%s%s has no tests available\n", __signal_empty, __file);
207 ## Add a dummy comment block to the end for ease of indexing.
208 if (__body (length(__body)) == "\n")
209 __body = sprintf ("\n%s#", __body);
211 __body = sprintf ("\n%s\n#", __body);
215 ## Chop it up into blocks for evaluation.
216 __lineidx = find (__body == "\n");
217 __blockidx = __lineidx(find (! isspace (__body(__lineidx+1))))+1;
219 ## Ready to start tests ... if in batch mode, tell us what is happening.
221 disp (cstrcat (__signal_file, __file));
224 ## Assume all tests will pass.
227 ## Process each block separately, initially with no shared variables.
228 __tests = __successes = 0;
232 for __i = 1:length(__blockidx)-1
234 ## Extract the block.
235 __block = __body(__blockidx(__i):__blockidx(__i+1)-2);
237 ## Let the user/logfile know what is happening.
239 fprintf (__fid, "%s%s\n", __signal_block, __block);
243 ## Split __block into __type and __code.
244 __idx = find (! isletter (__block));
249 __type = __block(1:__idx(1)-1);
250 __code = __block(__idx(1):length(__block));
253 ## Assume the block will succeed.
259 ## If in __grabdemo mode, then don't process any other block type.
260 ## So that the other block types don't have to worry about
261 ## this __grabdemo mode, the demo block processor grabs all block
262 ## types and skips those which aren't demo blocks.
264 __isdemo = strcmp (__type, "demo");
265 if (__grabdemo || __isdemo)
268 if (__grabdemo && __isdemo)
269 if (isempty(__demo_code))
270 __demo_code = __code;
271 __demo_idx = [1, length(__demo_code)+1];
273 __demo_code = cstrcat(__demo_code, __code);
274 __demo_idx = [__demo_idx, length(__demo_code)+1];
277 elseif (__rundemo && __isdemo)
279 ## process the code in an environment without variables
280 eval (sprintf ("function __test__()\n%s\nendfunction", __code));
282 input ("Press <enter> to continue: ", "s");
285 __msg = sprintf ("%sdemo failed\n%s", __signal_fail, __error_text__);
290 ## Code already processed.
295 elseif (strcmp (__type, "shared"))
298 ## Separate initialization code from variables.
299 __idx = find (__code == "\n");
304 __vars = __code (1:__idx(1)-1);
305 __code = __code (__idx(1):length(__code));
308 ## Strip comments off the variables.
309 __idx = find (__vars == "%" | __vars == "#");
310 if (! isempty (__idx))
311 __vars = __vars(1:__idx(1)-1);
314 ## Assign default values to variables.
316 __vars = deblank (__vars);
317 if (! isempty (__vars))
318 eval (cstrcat (strrep (__vars, ",", "=[];"), "=[];"));
320 __shared_r = cstrcat ("[ ", __vars, "] = ");
326 ## Couldn't declare, so don't initialize.
329 __msg = sprintf ("%sshared variable initialization failed\n",
333 ## Clear shared function definitions.
337 ## Initialization code will be evaluated below.
341 elseif (strcmp (__type, "function"))
344 __name_position = function_name (__block);
345 if (isempty (__name_position))
347 __msg = sprintf ("%stest failed: missing function name\n",
350 __name = __block(__name_position(1):__name_position(2));
353 eval(__code); ## Define the function
354 __clear = sprintf ("%sclear %s;\n", __clear, __name);
357 __msg = sprintf ("%stest failed: syntax error\n%s",
358 __signal_fail, __error_text__);
365 elseif (strcmp (__type, "assert") || strcmp (__type, "fail"))
367 ## Put the keyword back on the code.
369 ## The code will be evaluated below as a test block.
373 elseif (strcmp (__type, "error") || strcmp(__type, "warning"))
375 __warning = strcmp (__type, "warning");
376 [__pattern, __code] = getpattern (__code);
378 eval (sprintf ("function __test__(%s)\n%s\nendfunction",
382 __msg = sprintf ("%stest failed: syntax error\n%s",
383 __signal_fail, __error_text__);
388 __warnstate = warning ("query", "quiet");
389 warning ("on", "quiet");
391 eval (sprintf ("__test__(%s);", __shared));
393 __msg = sprintf ("%sexpected <%s> but got no error\n",
394 __signal_fail, __pattern);
396 __err = trimerr (lastwarn, "warning");
397 warning (__warnstate.state, "quiet");
399 __msg = sprintf ("%sexpected <%s> but got no warning\n",
400 __signal_fail, __pattern);
401 elseif (isempty (regexp (__err, __pattern, "once")))
402 __msg = sprintf ("%sexpected <%s> but got %s\n",
403 __signal_fail, __pattern, __err);
410 __err = trimerr (lasterr, "error");
411 warning (__warnstate.state, "quiet");
413 __msg = sprintf ("%sexpected warning <%s> but got error %s\n",
414 __signal_fail, __pattern, __err);
415 elseif (isempty (regexp (__err, __pattern, "once")))
416 __msg = sprintf ("%sexpected <%s> but got %s\n",
417 __signal_fail, __pattern, __err);
424 ## Code already processed.
429 elseif (strcmp (__type, "testif"))
430 [__e, __feat] = regexp (__code, '^\s*([^\s]+)', 'end', 'tokens');
431 if (isempty (findstr (octave_config_info ("DEFS"), __feat{1}{1})))
437 __msg = sprintf ("%sskipped test\n", __signal_skip);
440 __code = __code(__e + 1 : end);
445 elseif (strcmp (__type, "test") || strcmp (__type, "xtest"))
447 ## Code will be evaluated below.
451 elseif (strcmp (__block(1:1), "#"))
453 __code = ""; # skip the code
460 __msg = sprintf ("%sunknown test type!\n", __signal_fail);
461 __code = ""; # skip the code
464 ## evaluate code for test, shared, and assert.
465 if (! isempty(__code))
467 eval (sprintf ("function %s__test__(%s)\n%s\nendfunction",
468 __shared_r,__shared, __code));
469 eval (sprintf ("%s__test__(%s);", __shared_r, __shared));
471 if (strcmp (__type, "xtest"))
472 __msg = sprintf ("%sknown failure\n%s", __signal_fail, __error_text__);
475 __msg = sprintf ("%stest failed\n%s", __signal_fail, __error_text__);
478 if (isempty (__error_text__))
479 error ("empty error text, probably Ctrl-C --- aborting");
485 ## All done. Remember if we were successful and print any messages.
486 if (! isempty (__msg))
487 ## Make sure the user knows what caused the error.
489 fprintf (__fid, "%s%s\n", __signal_block, __block);
492 fputs (__fid, __msg);
495 ## Show the variable context.
496 if (! strcmp (__type, "error") && ! strcmp (__type, "testif")
497 && ! all (__shared == " "))
498 fputs (__fid, "shared variables ");
499 eval (sprintf ("fdisp(__fid,bundle(%s));", __shared));
505 ## Stop after one error if not in batch mode.
517 __successes += __success * __istest;
522 if (__tests || __xfail || __xskip)
524 printf ("PASSES %d out of %d tests (%d expected failures)\n",
525 __successes, __tests, __xfail);
527 printf ("PASSES %d out of %d tests\n", __successes, __tests);
530 printf ("Skipped %d tests due to missing features\n", __xskip);
533 printf ("%s%s has no tests available\n", __signal_empty, __file);
536 __ret1 = __demo_code;
538 elseif (nargout == 1)
539 __ret1 = __all_success;
541 __ret1 = __successes;
548## Create structure with fieldnames the name of the input variables.
549function s = varstruct (varargin)
551 s.(deblank (argn(i,:))) = varargin{i};
555## Find [start,end] of fn in 'function [a,b] = fn'.
556function pos = function_name (def)
559 ## Find the end of the name.
560 right = find (def == "(", 1);
564 right = find (def(1:right-1) != " ", 1, "last");
566 ## Find the beginning of the name.
567 left = max ([find(def(1:right)==" ", 1, "last"), ...
568 find(def(1:right)=="=", 1, "last")]);
574 ## Return the end points of the name.
578## Strip <pattern> from '<pattern> code'.
579function [pattern, rest] = getpattern (str)
582 str = trimleft (str);
583 if (! isempty (str) && str(1) == "<")
584 close = index (str, ">");
586 pattern = str(2:close-1);
587 rest = str(close+1:end);
592## Strip '.*prefix:' from '.*prefix: msg\n' and strip trailing blanks.
593function msg = trimerr (msg, prefix)
594 idx = index (msg, cstrcat (prefix, ":"));
596 msg(1:idx+length(prefix)) = [];
598 msg = trimleft (deblank (msg));
601## Strip leading blanks from string.
602function str = trimleft (str)
603 idx = find (isspace (str));
604 leading = find (idx == 1:length(idx));
605 if (! isempty (leading))
606 str = str(leading(end)+1:end);
610## Make a structure out of the named variables
611## (based on Etienne Grossmann's tar function).
612function s = bundle (varargin)
614 s.(deblank (argn(i,:))) = varargin{i};
618function body = __extract_test_code (nm)
619 fid = fopen (nm, "rt");
624 if (length (ln) >= 2 && strcmp (ln(1:2), "%!"))
627 body = cstrcat (body, ln(3:end));
635### Test for test for missing features
636%!testif OCTAVE_SOURCE
637%! ## This test should be run
640### Disable this test to avoid spurious skipped test for "make check"
642% ! ## missing feature. Fail if this test is run
643% ! error("Failed missing feature test");
645### Test for a known failure
646%!xtest error("This test is known to fail")
648### example from toeplitz
650%! msg="expecting vector arguments";
651%!fail ('toeplitz([])', msg);
652%!fail ('toeplitz([1,2],[])', msg);
653%!fail ('toeplitz([1,2;3,4])', msg);
654%!fail ('toeplitz([1,2],[1,2;3,4])', msg);
655%!fail ('toeplitz ([1,2;3,4],[1,2])', msg);
656% !fail ('toeplitz','usage: toeplitz'); # usage doesn't generate an error
657% !fail ('toeplitz(1, 2, 3)', 'usage: toeplitz');
658%!test assert (toeplitz ([1,2,3], [1,4]), [1,4; 2,1; 3,2]);
659%!demo toeplitz ([1,2,3,4],[1,5,6])
662%!#error kron # FIXME suppress these until we can handle output
664%!test assert (isempty (kron ([], rand(3, 4))))
665%!test assert (isempty (kron (rand (3, 4), [])))
666%!test assert (isempty (kron ([], [])))
669%! A = [1, 2, 3; 4, 5, 6];
670%! B = [1, -1; 2, -2];
671%!assert (size (kron (zeros (3, 0), A)), [ 3*rows(A), 0 ])
672%!assert (size (kron (zeros (0, 3), A)), [ 0, 3*columns(A) ])
673%!assert (size (kron (A, zeros (3, 0))), [ 3*rows(A), 0 ])
674%!assert (size (kron (A, zeros (0, 3))), [ 0, 3*columns(A) ])
675%!assert (kron (pi, e), pi*e)
676%!assert (kron (pi, A), pi*A)
677%!assert (kron (A, e), e*A)
678%!assert (kron ([1, 2, 3], A), [ A, 2*A, 3*A ])
679%!assert (kron ([1; 2; 3], A), [ A; 2*A; 3*A ])
680%!assert (kron ([1, 2; 3, 4], A), [ A, 2*A; 3*A, 4*A ])
682%! res = [1,-1,2,-2,3,-3; 2,-2,4,-4,6,-6; 4,-4,5,-5,6,-6; 8,-8,10,-10,12,-12];
683%! assert (kron (A, B), res)
685### an extended demo from specgram
687%! ## Speech spectrogram
688%! [x, Fs] = auload(file_in_loadpath("sample.wav")); # audio file
689%! step = fix(5*Fs/1000); # one spectral slice every 5 ms
690%! window = fix(40*Fs/1000); # 40 ms data window
691%! fftn = 2^nextpow2(window); # next highest power of 2
692%! [S, f, t] = specgram(x, fftn, Fs, window, window-step);
693%! S = abs(S(2:fftn*4000/Fs,:)); # magnitude in range 0<f<=4000 Hz.
694%! S = S/max(max(S)); # normalize magnitude so that max is 0 dB.
695%! S = max(S, 10^(-40/10)); # clip below -40 dB.
696%! S = min(S, 10^(-3/10)); # clip above -3 dB.
697%! imagesc(flipud(20*log10(S)), 1);
698%! % you should now see a spectrogram in the image window
701### now test test itself
703%!## usage and error testing
704% !fail ('test','usage.*test') # no args, generates usage()
705% !fail ('test(1,2,3,4)','usage.*test') # too many args, generates usage()
706%!fail ('test("test", "bogus")','unknown flag') # incorrect args
707%!fail ('garbage','garbage.*undefined') # usage on nonexistent function should be
709%!error test # no args, generates usage()
710%!error test(1,2,3,4) # too many args, generates usage()
711%!error <unknown flag> test("test", 'bogus'); # incorrect args, generates error()
712%!error <garbage' undefined> garbage # usage on nonexistent function should be
714%!error test("test", 'bogus'); # test without pattern
717%! lastwarn(); # clear last warning just in case
719%!warning <warning message> warning('warning message');
721%!## test of shared variables
722%!shared a # create a shared variable
723%!test a=3; # assign to a shared variable
724%!test assert(a,3) # variable should equal 3
725%!shared b,c # replace shared variables
726%!test assert (!exist("a")); # a no longer exists
727%!test assert (isempty(b)); # variables start off empty
728%!shared a,b,c # recreate a shared variable
729%!test assert (isempty(a)); # value is empty even if it had a previous value
730%!test a=1; b=2; c=3; # give values to all variables
731%!test assert ([a,b,c],[1,2,3]); # test all of them together
732%!test c=6; # update a value
733%!test assert([a, b, c],[1, 2, 6]); # show that the update sticks
734%!shared # clear all shared variables
735%!test assert(!exist("a")) # show that they are cleared
736%!shared a,b,c # support for initializer shorthand
739%!function x = __test_a(y)
741%!assert(__test_a(2),4); # Test a test function
743%!function __test_a (y)
746%! __test_a(2); # Test a test function with no return value
748%!function [x,z] = __test_a (y)
751%!test # Test a test function with multiple returns
752%! [x,z] = __test_a(3);
756%!## test of assert block
757%!assert (isempty([])) # support for test assert shorthand
760%!demo # multiline demo block
761%! t=[0:0.01:2*pi]; x=sin(t);
763%! % you should now see a sine wave in your figure window
764%!demo a=3 # single line demo blocks work too
766%!## this is a comment block. it can contain anything.
768%! it is the "#" as the block type that makes it a comment
769%! and it stays as a comment even through continuation lines
770%! which means that it works well with commenting out whole tests
772% !# failure tests. All the following should fail. These tests should
773% !# be disabled unless you are developing test() since users don't
774% !# like to be presented with expected failures. I use % ! to disable.
775% !test error("---------Failure tests. Use test('test','verbose',1)");
776% !test assert([a,b,c],[1,3,6]); # variables have wrong values
777% !bogus # unknown block type
778% !error toeplitz([1,2,3]); # correct usage
779% !test syntax errors) # syntax errors fail properly
780% !shared garbage in # variables must be comma separated
781% !error syntax++error # error test fails on syntax errors
782% !error "succeeds."; # error test fails if code succeeds
783% !error <wrong pattern> error("message") # error pattern must match
784% !demo with syntax error # syntax errors in demo fail properly
786% !demo # shared variables not available in demo
787% ! assert(exist("a"))
789% ! test('/etc/passwd');
790% ! test("nonexistent file");
791% ! ## These don't signal an error, so the test for an error fails. Note
792% ! ## that the call doesn't reference the current fid (it is unavailable),
793% ! ## so of course the informational message is not printed in the log.