]> Creatis software - CreaPhase.git/blob - octave_packages/m/testfun/test.m
update packages
[CreaPhase.git] / octave_packages / m / testfun / test.m
1 ## Copyright (C) 2005-2012 Paul Kienzle
2 ##
3 ## This file is part of Octave.
4 ##
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.
9 ##
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.
14 ##
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/>.
18
19 ## -*- texinfo -*-
20 ## @deftypefn  {Command} {} test @var{name}
21 ## @deftypefnx {Command} {} 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')
27 ##
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.
32 ##
33 ## With a second argument the tests which are performed and the amount of
34 ## output is selected.
35 ##
36 ## @table @asis
37 ## @item 'quiet'
38 ##  Don't report all the tests as they happen, just the errors.
39 ##
40 ## @item 'normal'
41 ## Report all tests as they happen, but don't do tests which require
42 ## user interaction.
43 ##
44 ## @item 'verbose'
45 ## Do tests which require user interaction.
46 ## @end table
47 ##
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
54 ## the current test.
55 ##
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.
60 ##
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.
65 ##
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{assert, fail, error, demo, example}
69 ## @end deftypefn
70
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.
75
76 function [__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 = "----- ";
83
84   __xfail = 0;
85   __xskip = 0;
86
87   if (nargin < 2 || isempty (__flag))
88     __flag = "quiet";
89   endif
90   if (nargin < 3)
91     __fid = [];
92   endif
93   if (nargin < 1 || nargin > 3
94       || (! ischar (__name) && ! isempty (__name)) || ! ischar (__flag))
95     print_usage ();
96   endif
97   if (isempty (__name) && (nargin != 3 || ! strcmp (__flag, "explain")))
98     print_usage ();
99   endif
100   __batch = (! isempty (__fid));
101
102   ## Decide if error messages should be collected.
103   __close_fid = 0;
104   if (__batch)
105     if (ischar (__fid))
106       __fid = fopen (__fid, "wt");
107       if (__fid < 0)
108         error ("test: could not open log file");
109       endif
110       __close_fid = 1;
111     endif
112     fprintf (__fid, "%sprocessing %s\n", __signal_file, __name);
113     fflush (__fid);
114   else
115     __fid = stdout;
116   endif
117
118   if (strcmp (__flag, "normal"))
119     __grabdemo = 0;
120     __rundemo = 0;
121     __verbose = __batch;
122   elseif (strcmp (__flag, "quiet"))
123     __grabdemo = 0;
124     __rundemo = 0;
125     __verbose = 0;
126   elseif (strcmp (__flag, "verbose"))
127     __grabdemo = 0;
128     __rundemo = 1;
129     __verbose = 1;
130   elseif (strcmp (__flag, "grabdemo"))
131     __grabdemo = 1;
132     __rundemo = 0;
133     __verbose = 0;
134     __demo_code = "";
135     __demo_idx = [];
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");
146     fflush (__fid);
147     if (__close_fid)
148       fclose(__fid);
149     endif
150     return;
151   else
152     error ("test: unknown flag '%s'", __flag);
153   endif
154
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");
159   endif
160   if (isempty (__file))
161     __file = file_in_loadpath (cstrcat (__name, ".cc"), "all");
162   endif
163   if (iscell (__file))
164       ## If repeats, return first in path.
165     if (isempty (__file))
166       __file = "";
167     else
168       __file = __file{1};
169     endif
170   endif
171   if (isempty (__file))
172     if (__grabdemo)
173       __ret1 = "";
174       __ret2 = [];
175     else
176       if (exist (__name) == 3)
177         fprintf (__fid, "%s%s source code with tests for dynamically linked function not found\n", __signal_empty, __name);
178       else
179         fprintf (__fid, "%s%s does not exist in path\n", __signal_empty, __name);
180       endif
181       fflush (__fid);
182       if (nargout > 0)
183         __ret1 = __ret2 = 0;
184       endif
185     endif
186     if (__close_fid)
187       fclose(__fid);
188     endif
189     return;
190   endif
191
192   ## Grab the test code from the file.
193   __body = __extract_test_code (__file);
194
195   if (isempty (__body))
196     if (__grabdemo)
197       __ret1 = "";
198       __ret2 = [];
199     else
200       fprintf (__fid, "%s%s has no tests available\n", __signal_empty, __file);
201       fflush (__fid);
202       if (nargout > 0)
203         __ret1 = __ret2 = 0;
204       endif
205     endif
206     if (__close_fid)
207       fclose(__fid);
208     endif
209     return;
210   else
211     ## Add a dummy comment block to the end for ease of indexing.
212     if (__body (length(__body)) == "\n")
213       __body = sprintf ("\n%s#", __body);
214     else
215       __body = sprintf ("\n%s\n#", __body);
216     endif
217   endif
218
219   ## Chop it up into blocks for evaluation.
220   __lineidx = find (__body == "\n");
221   __blockidx = __lineidx(find (! isspace (__body(__lineidx+1))))+1;
222
223   ## Ready to start tests ... if in batch mode, tell us what is happening.
224   if (__verbose)
225     disp (cstrcat (__signal_file, __file));
226   endif
227
228   ## Assume all tests will pass.
229   __all_success = 1;
230
231   ## Process each block separately, initially with no shared variables.
232   __tests = __successes = 0;
233   __shared = " ";
234   __shared_r = " ";
235   __clear = "";
236   for __i = 1:length(__blockidx)-1
237
238     ## Extract the block.
239     __block = __body(__blockidx(__i):__blockidx(__i+1)-2);
240
241     ## Let the user/logfile know what is happening.
242     if (__verbose)
243       fprintf (__fid, "%s%s\n", __signal_block, __block);
244       fflush (__fid);
245     endif
246
247     ## Split __block into __type and __code.
248     __idx = find (! isletter (__block));
249     if (isempty (__idx))
250       __type = __block;
251       __code = "";
252     else
253       __type = __block(1:__idx(1)-1);
254       __code = __block(__idx(1):length(__block));
255     endif
256
257     ## Assume the block will succeed.
258     __success = 1;
259     __msg = [];
260
261 ### DEMO
262
263     ## If in __grabdemo mode, then don't process any other block type.
264     ## So that the other block types don't have to worry about
265     ## this __grabdemo mode, the demo block processor grabs all block
266     ## types and skips those which aren't demo blocks.
267
268     __isdemo = strcmp (__type, "demo");
269     if (__grabdemo || __isdemo)
270       __istest = 0;
271
272       if (__grabdemo && __isdemo)
273         if (isempty(__demo_code))
274           __demo_code = __code;
275           __demo_idx = [1, length(__demo_code)+1];
276         else
277           __demo_code = cstrcat(__demo_code, __code);
278           __demo_idx = [__demo_idx, length(__demo_code)+1];
279         endif
280
281       elseif (__rundemo && __isdemo)
282         try
283           ## process the code in an environment without variables
284           eval (sprintf ("function __test__()\n%s\nendfunction", __code));
285           __test__;
286           input ("Press <enter> to continue: ", "s");
287         catch
288           __success = 0;
289           __msg = sprintf ("%sdemo failed\n%s",  __signal_fail, lasterr ());
290         end_try_catch
291         clear __test__;
292
293       endif
294       ## Code already processed.
295       __code = "";
296
297 ### SHARED
298
299     elseif (strcmp (__type, "shared"))
300       __istest = 0;
301
302       ## Separate initialization code from variables.
303       __idx = find (__code == "\n");
304       if (isempty (__idx))
305         __vars = __code;
306         __code = "";
307       else
308         __vars = __code (1:__idx(1)-1);
309         __code = __code (__idx(1):length(__code));
310       endif
311
312       ## Strip comments off the variables.
313       __idx = find (__vars == "%" | __vars == "#");
314       if (! isempty (__idx))
315         __vars = __vars(1:__idx(1)-1);
316       endif
317
318       ## Assign default values to variables.
319       try
320         __vars = deblank (__vars);
321         if (! isempty (__vars))
322           eval (cstrcat (strrep (__vars, ",", "=[];"), "=[];"));
323           __shared = __vars;
324           __shared_r = cstrcat ("[ ", __vars, "] = ");
325         else
326           __shared = " ";
327           __shared_r = " ";
328         endif
329       catch
330         ## Couldn't declare, so don't initialize.
331         __code = "";
332         __success = 0;
333         __msg = sprintf ("%sshared variable initialization failed\n",
334                          __signal_fail);
335       end_try_catch
336
337       ## Clear shared function definitions.
338       eval (__clear, "");
339       __clear = "";
340
341       ## Initialization code will be evaluated below.
342
343 ### FUNCTION
344
345     elseif (strcmp (__type, "function"))
346       __istest = 0;
347       persistent __fn = 0;
348       __name_position = function_name (__block);
349       if (isempty (__name_position))
350         __success = 0;
351         __msg = sprintf ("%stest failed: missing function name\n",
352                          __signal_fail);
353       else
354         __name = __block(__name_position(1):__name_position(2));
355         __code = __block;
356         try
357           eval(__code); ## Define the function
358           __clear = sprintf ("%sclear %s;\n", __clear, __name);
359         catch
360           __success = 0;
361           __msg = sprintf ("%stest failed: syntax error\n%s",
362                            __signal_fail, lasterr ());
363         end_try_catch
364       endif
365       __code = "";
366
367 ### ENDFUNCTION
368
369     elseif (strcmp (__type, "endfunction"))
370       ## endfunction simply declares the end of a previous function block.
371       ## There is no processing to be done here, just skip to next block.
372       __istest = 0;
373       __code = "";
374
375 ### ASSERT/FAIL
376
377     elseif (strcmp (__type, "assert") || strcmp (__type, "fail"))
378       __istest = 1;
379       ## Put the keyword back on the code.
380       __code = __block;
381       ## The code will be evaluated below as a test block.
382
383 ### ERROR/WARNING
384
385     elseif (strcmp (__type, "error") || strcmp(__type, "warning"))
386       __istest = 1;
387       __warning = strcmp (__type, "warning");
388       [__pattern, __id, __code] = getpattern (__code);
389       if (__id)
390         __patstr = ["id=",__id];
391       else
392         __patstr = ["<",__pattern,">"];
393       endif
394       try
395         eval (sprintf ("function __test__(%s)\n%s\nendfunction",
396                        __shared, __code));
397       catch
398         __success = 0;
399         __msg = sprintf ("%stest failed: syntax error\n%s",
400                          __signal_fail, lasterr ());
401       end_try_catch
402
403       if (__success)
404         __success = 0;
405         __warnstate = warning ("query", "quiet");
406         warning ("on", "quiet");
407         try
408           eval (sprintf ("__test__(%s);", __shared));
409           if (! __warning)
410             __msg = sprintf ("%sexpected %s but got no error\n",
411                              __signal_fail, __patstr);
412           else
413             if (! isempty (__id))
414               [~, __err] = lastwarn;
415               __mismatch = ! strcmp (__err, __id);
416             else
417               __err = trimerr (lastwarn, "warning");
418               __mismatch = isempty (regexp (__err, __pattern, "once"));
419             endif
420             warning (__warnstate.state, "quiet");
421             if (isempty (__err))
422               __msg = sprintf ("%sexpected %s but got no warning\n",
423                              __signal_fail, __patstr);
424             elseif (__mismatch)
425               __msg = sprintf ("%sexpected %s but got %s\n",
426                                __signal_fail, __patstr, __err);
427             else
428               __success = 1;
429             endif
430           endif
431
432         catch
433           if (! isempty (__id))
434             [~, __err] = lasterr;
435             __mismatch = ! strcmp (__err, __id);
436           else
437             __err = trimerr (lasterr, "error");
438             __mismatch = isempty (regexp (__err, __pattern, "once"));
439           endif
440           warning (__warnstate.state, "quiet");
441           if (__warning)
442             __msg = sprintf ("%sexpected warning %s but got error %s\n",
443                              __signal_fail, __patstr, __err);
444           elseif (__mismatch)
445             __msg = sprintf ("%sexpected %s but got %s\n",
446                              __signal_fail, __patstr, __err);
447           else
448             __success = 1;
449           endif
450         end_try_catch
451         clear __test__;
452       endif
453       ## Code already processed.
454       __code = "";
455
456 ### TESTIF
457
458     elseif (strcmp (__type, "testif"))
459       __e = regexp (__code, '.$', 'lineanchors', 'once');
460       ## Strip comment any comment from testif line before looking for features
461       __feat_line = strtok (__code(1:__e), '#%'); 
462       __feat = regexp (__feat_line, '\w+', 'match');
463       __have_feat = strfind (octave_config_info ("DEFS"), __feat); 
464       if (any (cellfun ("isempty", __have_feat)))
465         __xskip++;
466         __istest = 0;
467         __code = ""; # Skip the code.
468         __msg = sprintf ("%sskipped test\n", __signal_skip);
469       else
470         __istest = 1;
471         __code = __code(__e + 1 : end);
472       endif
473
474 ### TEST
475
476     elseif (strcmp (__type, "test") || strcmp (__type, "xtest"))
477       __istest = 1;
478       ## Code will be evaluated below.
479
480 ### Comment block.
481
482     elseif (strcmp (__block(1:1), "#"))
483       __istest = 0;
484       __code = ""; # skip the code
485
486 ### Unknown block.
487
488     else
489       __istest = 1;
490       __success = 0;
491       __msg = sprintf ("%sunknown test type!\n", __signal_fail);
492       __code = ""; # skip the code
493     endif
494
495     ## evaluate code for test, shared, and assert.
496     if (! isempty(__code))
497       try
498         ## FIXME: need to check for embedded test functions, which cause
499         ## segfaults, until issues with subfunctions in functions are resolved.
500         embed_func = regexp (__code, '^\s*function ', 'once', 'lineanchors');
501         if (isempty (embed_func))
502           eval (sprintf ("function %s__test__(%s)\n%s\nendfunction",
503                          __shared_r,__shared, __code));
504           eval (sprintf ("%s__test__(%s);", __shared_r, __shared));
505         else
506           error (["Functions embedded in %!test blocks are not allowed.\n", ...
507                   "Use the %!function/%!endfunction syntax instead to define shared functions for testing.\n"]);
508         endif
509       catch
510         if (strcmp (__type, "xtest"))
511            __msg = sprintf ("%sknown failure\n%s", __signal_fail, lasterr ());
512            __xfail++;
513         else
514            __msg = sprintf ("%stest failed\n%s", __signal_fail, lasterr ());
515            __success = 0;
516         endif
517         if (isempty (lasterr ()))
518           error ("empty error text, probably Ctrl-C --- aborting");
519         endif
520       end_try_catch
521       clear __test__;
522     endif
523
524     ## All done.  Remember if we were successful and print any messages.
525     if (! isempty (__msg))
526       ## Make sure the user knows what caused the error.
527       if (! __verbose)
528         fprintf (__fid, "%s%s\n", __signal_block, __block);
529         fflush (__fid);
530       endif
531       fputs (__fid, __msg);
532       fputs (__fid, "\n");
533       fflush (__fid);
534       ## Show the variable context.
535       if (! strcmp (__type, "error") && ! strcmp (__type, "testif")
536           && ! all (__shared == " "))
537         fputs (__fid, "shared variables ");
538         eval (sprintf ("fdisp(__fid,bundle(%s));", __shared));
539         fflush (__fid);
540       endif
541     endif
542     if (__success == 0)
543       __all_success = 0;
544       ## Stop after one error if not in batch mode.
545       if (! __batch)
546         if (nargout > 0)
547           __ret1 = __ret2 = 0;
548         endif
549         if (__close_fid)
550           fclose(__fid);
551         endif
552         return;
553       endif
554     endif
555     __tests += __istest;
556     __successes += __success * __istest;
557   endfor
558   eval (__clear, "");
559
560   if (nargout == 0)
561     if (__tests || __xfail || __xskip)
562       if (__xfail)
563         printf ("PASSES %d out of %d tests (%d expected failures)\n",
564                 __successes, __tests, __xfail);
565       else
566         printf ("PASSES %d out of %d tests\n", __successes, __tests);
567       endif
568       if (__xskip)
569         printf ("Skipped %d tests due to missing features\n", __xskip);
570       endif
571     else
572       printf ("%s%s has no tests available\n", __signal_empty, __file);
573     endif
574   elseif (__grabdemo)
575     __ret1 = __demo_code;
576     __ret2 = __demo_idx;
577   elseif (nargout == 1)
578     __ret1 = __all_success;
579   else
580     __ret1 = __successes;
581     __ret2 = __tests;
582     __ret3 = __xfail;
583     __ret4 = __xskip;
584   endif
585 endfunction
586
587 ## Create structure with fieldnames the name of the input variables.
588 function s = varstruct (varargin)
589   for i = 1:nargin
590     s.(deblank (argn(i,:))) = varargin{i};
591   endfor
592 endfunction
593
594 ## Find [start,end] of fn in 'function [a,b] = fn'.
595 function pos = function_name (def)
596   pos = [];
597
598   ## Find the end of the name.
599   right = find (def == "(", 1);
600   if (isempty (right))
601     return;
602   endif
603   right = find (def(1:right-1) != " ", 1, "last");
604
605   ## Find the beginning of the name.
606   left = max ([find(def(1:right)==" ", 1, "last"), ...
607                find(def(1:right)=="=", 1, "last")]);
608   if (isempty (left))
609     return;
610   endif
611   left++;
612
613   ## Return the end points of the name.
614   pos = [left, right];
615 endfunction
616
617 ## Strip <pattern> from '<pattern> code'.
618 ## Also handles 'id=ID code'
619 function [pattern, id, rest] = getpattern (str)
620   pattern = ".";
621   id = [];
622   rest = str;
623   str = trimleft (str);
624   if (! isempty (str) && str(1) == "<")
625     close = index (str, ">");
626     if (close)
627       pattern = str(2:close-1);
628       rest = str(close+1:end);
629     endif
630   elseif (strncmp (str, "id=", 3))
631     [id, rest] = strtok (str(4:end));
632   endif
633 endfunction
634
635 ## Strip '.*prefix:' from '.*prefix: msg\n' and strip trailing blanks.
636 function msg = trimerr (msg, prefix)
637   idx = index (msg, cstrcat (prefix, ":"));
638   if (idx > 0)
639     msg(1:idx+length(prefix)) = [];
640   endif
641   msg = trimleft (deblank (msg));
642 endfunction
643
644 ## Strip leading blanks from string.
645 function str = trimleft (str)
646   idx = find (isspace (str));
647   leading = find (idx == 1:length(idx));
648   if (! isempty (leading))
649     str = str(leading(end)+1:end);
650   endif
651 endfunction
652
653 ## Make a structure out of the named variables
654 ## (based on Etienne Grossmann's tar function).
655 function s = bundle (varargin)
656   for i = 1:nargin
657     s.(deblank (argn(i,:))) = varargin{i};
658   endfor
659 endfunction
660
661 function body = __extract_test_code (nm)
662   fid = fopen (nm, "rt");
663   body = [];
664   if (fid >= 0)
665     while (! feof (fid))
666       ln = fgetl (fid);
667       if (length (ln) >= 2 && strcmp (ln(1:2), "%!"))
668         body = [body, "\n"];
669         if (length(ln) > 2)
670           body = cstrcat (body, ln(3:end));
671         endif
672       endif
673     endwhile
674     fclose (fid);
675   endif
676 endfunction
677
678 ### Test for test for missing features
679 %!testif OCTAVE_SOURCE
680 %! ## This test should be run
681 %! assert (true);
682
683 ### Disable this test to avoid spurious skipped test for "make check"
684 % !testif HAVE_FOOBAR
685 % ! ## missing feature. Fail if this test is run
686 % ! error("Failed missing feature test");
687
688 ### Test for a known failure
689 %!xtest error("This test is known to fail")
690
691 ### example from toeplitz
692 %!shared msg1,msg2
693 %! msg1="C must be a vector";
694 %! msg2="C and R must be vectors";
695 %!fail ('toeplitz([])', msg1);
696 %!fail ('toeplitz([1,2;3,4])', msg1);
697 %!fail ('toeplitz([1,2],[])', msg2);
698 %!fail ('toeplitz([1,2],[1,2;3,4])', msg2);
699 %!fail ('toeplitz ([1,2;3,4],[1,2])', msg2);
700 % !fail ('toeplitz','usage: toeplitz'); # usage doesn't generate an error
701 % !fail ('toeplitz(1, 2, 3)', 'usage: toeplitz');
702 %!test  assert (toeplitz ([1,2,3], [1,4]), [1,4; 2,1; 3,2]);
703 %!demo  toeplitz ([1,2,3,4],[1,5,6])
704
705 ### example from kron
706 %!#error kron  # FIXME suppress these until we can handle output
707 %!#error kron(1,2,3)
708 %!test assert (isempty (kron ([], rand(3, 4))))
709 %!test assert (isempty (kron (rand (3, 4), [])))
710 %!test assert (isempty (kron ([], [])))
711 %!shared A, B
712 %!test
713 %! A = [1, 2, 3; 4, 5, 6];
714 %! B = [1, -1; 2, -2];
715 %!assert (size (kron (zeros (3, 0), A)), [ 3*rows(A), 0 ])
716 %!assert (size (kron (zeros (0, 3), A)), [ 0, 3*columns(A) ])
717 %!assert (size (kron (A, zeros (3, 0))), [ 3*rows(A), 0 ])
718 %!assert (size (kron (A, zeros (0, 3))), [ 0, 3*columns(A) ])
719 %!assert (kron (pi, e), pi*e)
720 %!assert (kron (pi, A), pi*A)
721 %!assert (kron (A, e), e*A)
722 %!assert (kron ([1, 2, 3], A), [ A, 2*A, 3*A ])
723 %!assert (kron ([1; 2; 3], A), [ A; 2*A; 3*A ])
724 %!assert (kron ([1, 2; 3, 4], A), [ A, 2*A; 3*A, 4*A ])
725 %!test
726 %! 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];
727 %! assert (kron (A, B), res)
728
729 ### an extended demo from specgram
730 %!#demo
731 %! ## Speech spectrogram
732 %! [x, Fs] = auload(file_in_loadpath("sample.wav")); # audio file
733 %! step = fix(5*Fs/1000);     # one spectral slice every 5 ms
734 %! window = fix(40*Fs/1000);  # 40 ms data window
735 %! fftn = 2^nextpow2(window); # next highest power of 2
736 %! [S, f, t] = specgram(x, fftn, Fs, window, window-step);
737 %! S = abs(S(2:fftn*4000/Fs,:)); # magnitude in range 0<f<=4000 Hz.
738 %! S = S/max(max(S));         # normalize magnitude so that max is 0 dB.
739 %! S = max(S, 10^(-40/10));   # clip below -40 dB.
740 %! S = min(S, 10^(-3/10));    # clip above -3 dB.
741 %! imagesc(flipud(20*log10(S)), 1);
742 %! % you should now see a spectrogram in the image window
743
744
745 ### now test test itself
746
747 %!## usage and error testing
748 % !fail ('test','usage.*test')           # no args, generates usage()
749 % !fail ('test(1,2,3,4)','usage.*test')  # too many args, generates usage()
750 %!fail ('test("test", "bogus")','unknown flag')      # incorrect args
751 %!fail ('garbage','garbage.*undefined')  # usage on nonexistent function should be
752
753 %!error test                     # no args, generates usage()
754 %!error test(1,2,3,4)            # too many args, generates usage()
755 %!error <unknown flag> test("test", 'bogus');  # incorrect args, generates error()
756 %!error <garbage' undefined> garbage           # usage on nonexistent function should be
757
758 %!error test("test", 'bogus');           # test without pattern
759
760 %!test
761 %! lastwarn();            # clear last warning just in case
762
763 %!warning <warning message> warning('warning message');
764
765 %!## test of shared variables
766 %!shared a                # create a shared variable
767 %!test   a=3;             # assign to a shared variable
768 %!test   assert(a,3)      # variable should equal 3
769 %!shared b,c              # replace shared variables
770 %!test assert (!exist("a"));   # a no longer exists
771 %!test assert (isempty(b));    # variables start off empty
772 %!shared a,b,c            # recreate a shared variable
773 %!test assert (isempty(a));    # value is empty even if it had a previous value
774 %!test a=1; b=2; c=3;   # give values to all variables
775 %!test assert ([a,b,c],[1,2,3]); # test all of them together
776 %!test c=6;             # update a value
777 %!test assert([a, b, c],[1, 2, 6]); # show that the update sticks
778 %!shared                    # clear all shared variables
779 %!test assert(!exist("a"))  # show that they are cleared
780 %!shared a,b,c              # support for initializer shorthand
781 %! a=1; b=2; c=4;
782
783 %!function x = __test_a(y)
784 %! x = 2*y;
785 %!endfunction
786 %!assert(__test_a(2),4);       # Test a test function
787
788 %!function __test_a (y)
789 %! x = 2*y;
790 %!endfunction
791 %!test
792 %! __test_a(2);                # Test a test function with no return value
793
794 %!function [x,z] = __test_a (y)
795 %! x = 2*y;
796 %! z = 3*y;
797 %!endfunction
798 %!test                   # Test a test function with multiple returns
799 %! [x,z] = __test_a(3);
800 %! assert(x,6);
801 %! assert(z,9);
802
803 %!## test of assert block
804 %!assert (isempty([]))      # support for test assert shorthand
805
806 %!## demo blocks
807 %!demo                   # multiline demo block
808 %! t=[0:0.01:2*pi]; x=sin(t);
809 %! plot(t,x);
810 %! % you should now see a sine wave in your figure window
811 %!demo a=3               # single line demo blocks work too
812
813 %!## this is a comment block. it can contain anything.
814 %!##
815 %! it is the "#" as the block type that makes it a comment
816 %! and it  stays as a comment even through continuation lines
817 %! which means that it works well with commenting out whole tests
818
819 % !# failure tests.  All the following should fail. These tests should
820 % !# be disabled unless you are developing test() since users don't
821 % !# like to be presented with expected failures.  I use % ! to disable.
822 % !test   error("---------Failure tests.  Use test('test','verbose',1)");
823 % !test   assert([a,b,c],[1,3,6]);   # variables have wrong values
824 % !bogus                     # unknown block type
825 % !error  toeplitz([1,2,3]); # correct usage
826 % !test   syntax errors)     # syntax errors fail properly
827 % !shared garbage in         # variables must be comma separated
828 % !error  syntax++error      # error test fails on syntax errors
829 % !error  "succeeds.";       # error test fails if code succeeds
830 % !error <wrong pattern> error("message")  # error pattern must match
831 % !demo   with syntax error  # syntax errors in demo fail properly
832 % !shared a,b,c
833 % !demo                      # shared variables not available in demo
834 % ! assert(exist("a"))
835 % !error
836 % ! test('/etc/passwd');
837 % ! test("nonexistent file");
838 % ! ## These don't signal an error, so the test for an error fails. Note
839 % ! ## that the call doesn't reference the current fid (it is unavailable),
840 % ! ## so of course the informational message is not printed in the log.