view scripts/testfun/test.m @ 19627:446c46af4b42 stable

strip trailing whitespace from most source files * Makefile.am, NEWS, build-aux/common.mk, configure.ac, doc/Makefile.am, doc/doxyhtml/Makefile.am, doc/interpreter/Makefile.am, doc/interpreter/arith.txi, doc/interpreter/audio.txi, doc/interpreter/basics.txi, doc/interpreter/bugs.txi, doc/interpreter/container.txi, doc/interpreter/cp-idx.txi, doc/interpreter/data.txi, doc/interpreter/debug.txi, doc/interpreter/diagperm.txi, doc/interpreter/diffeq.txi, doc/interpreter/doccheck/README, doc/interpreter/doccheck/spellcheck, doc/interpreter/emacs.txi, doc/interpreter/errors.txi, doc/interpreter/eval.txi, doc/interpreter/expr.txi, doc/interpreter/external.txi, doc/interpreter/fn-idx.txi, doc/interpreter/func.txi, doc/interpreter/geometry.txi, doc/interpreter/geometryimages.m, doc/interpreter/gpl.txi, doc/interpreter/grammar.txi, doc/interpreter/gui.txi, doc/interpreter/image.txi, doc/interpreter/install.txi, doc/interpreter/interp.txi, doc/interpreter/interpimages.m, doc/interpreter/intro.txi, doc/interpreter/io.txi, doc/interpreter/java.txi, doc/interpreter/linalg.txi, doc/interpreter/macros.texi, doc/interpreter/matrix.txi, doc/interpreter/munge-texi.pl, doc/interpreter/nonlin.txi, doc/interpreter/numbers.txi, doc/interpreter/obsolete.txi, doc/interpreter/octave-config.1, doc/interpreter/octave.texi, doc/interpreter/oop.txi, doc/interpreter/op-idx.txi, doc/interpreter/optim.txi, doc/interpreter/package.txi, doc/interpreter/plot.txi, doc/interpreter/poly.txi, doc/interpreter/preface.txi, doc/interpreter/quad.txi, doc/interpreter/set.txi, doc/interpreter/signal.txi, doc/interpreter/sparse.txi, doc/interpreter/sparseimages.m, doc/interpreter/splineimages.m, doc/interpreter/stats.txi, doc/interpreter/stmt.txi, doc/interpreter/strings.txi, doc/interpreter/system.txi, doc/interpreter/testfun.txi, doc/interpreter/tips.txi, doc/interpreter/var.txi, doc/interpreter/vectorize.txi, doc/liboctave/Makefile.am, doc/liboctave/array.texi, doc/liboctave/bugs.texi, doc/liboctave/cp-idx.texi, doc/liboctave/dae.texi, doc/liboctave/diffeq.texi, doc/liboctave/error.texi, doc/liboctave/factor.texi, doc/liboctave/fn-idx.texi, doc/liboctave/gpl.texi, doc/liboctave/install.texi, doc/liboctave/intro.texi, doc/liboctave/liboctave.texi, doc/liboctave/matvec.texi, doc/liboctave/nleqn.texi, doc/liboctave/nlfunc.texi, doc/liboctave/ode.texi, doc/liboctave/optim.texi, doc/liboctave/preface.texi, doc/liboctave/quad.texi, doc/liboctave/range.texi, doc/refcard/Makefile.am, doc/refcard/refcard.tex, etc/HACKING, etc/NEWS.1, etc/NEWS.2, etc/NEWS.3, etc/OLD-ChangeLogs/ChangeLog, etc/OLD-ChangeLogs/doc-ChangeLog, etc/OLD-ChangeLogs/scripts-ChangeLog, etc/OLD-ChangeLogs/src-ChangeLog, etc/OLD-ChangeLogs/test-ChangeLog, etc/PROJECTS, etc/README.Cygwin, etc/README.MacOS, etc/README.MinGW, etc/README.gnuplot, etc/gdbinit, etc/icons/Makefile.am, examples/@polynomial/end.m, examples/@polynomial/subsasgn.m, examples/Makefile.am, examples/standalonebuiltin.cc, libgui/Makefile.am, libgui/qterminal/libqterminal/README, libgui/qterminal/libqterminal/unix/BlockArray.cpp, libgui/qterminal/libqterminal/unix/BlockArray.h, libgui/qterminal/libqterminal/unix/Character.h, libgui/qterminal/libqterminal/unix/CharacterColor.h, libgui/qterminal/libqterminal/unix/Emulation.cpp, libgui/qterminal/libqterminal/unix/Emulation.h, libgui/qterminal/libqterminal/unix/Filter.cpp, libgui/qterminal/libqterminal/unix/Filter.h, libgui/qterminal/libqterminal/unix/History.cpp, libgui/qterminal/libqterminal/unix/History.h, libgui/qterminal/libqterminal/unix/KeyboardTranslator.cpp, libgui/qterminal/libqterminal/unix/KeyboardTranslator.h, libgui/qterminal/libqterminal/unix/LineFont.h, libgui/qterminal/libqterminal/unix/QUnixTerminalImpl.cpp, libgui/qterminal/libqterminal/unix/QUnixTerminalImpl.h, libgui/qterminal/libqterminal/unix/Screen.cpp, libgui/qterminal/libqterminal/unix/Screen.h, libgui/qterminal/libqterminal/unix/ScreenWindow.cpp, libgui/qterminal/libqterminal/unix/ScreenWindow.h, libgui/qterminal/libqterminal/unix/TerminalCharacterDecoder.cpp, libgui/qterminal/libqterminal/unix/TerminalCharacterDecoder.h, libgui/qterminal/libqterminal/unix/Vt102Emulation.h, libgui/qterminal/libqterminal/win32/QWinTerminalImpl.cpp, libgui/qterminal/qterminal/main.cpp, libgui/src/m-editor/file-editor-tab.cc, libgui/src/octave-gui.cc, libgui/src/octave-qt-link.cc, libinterp/corefcn/data.cc, libinterp/corefcn/defun-int.h, libinterp/corefcn/det.cc, libinterp/corefcn/gl2ps-renderer.cc, libinterp/corefcn/graphics.cc, libinterp/corefcn/graphics.in.h, libinterp/corefcn/ls-mat5.cc, libinterp/corefcn/lu.cc, libinterp/corefcn/oct-tex-parser.yy, libinterp/corefcn/oct-tex-symbols.in, libinterp/corefcn/quadcc.cc, libinterp/corefcn/zfstream.cc, libinterp/dldfcn/__eigs__.cc, libinterp/dldfcn/__voronoi__.cc, libinterp/gendoc.pl, libinterp/genprops.awk, libinterp/mk-errno-list, libinterp/mk-pkg-add, libinterp/mkbuiltins, libinterp/mkdefs, libinterp/mkdocs, libinterp/mkops, libinterp/octave-value/ov-java.cc, libinterp/parse-tree/lex.ll, libinterp/parse-tree/oct-parse.in.yy, libinterp/parse-tree/octave.gperf, liboctave/Makefile.am, liboctave/array/Array.cc, liboctave/array/module.mk, liboctave/cruft/daspk/datv.f, liboctave/cruft/daspk/dcnst0.f, liboctave/cruft/daspk/dcnstr.f, liboctave/cruft/daspk/ddasic.f, liboctave/cruft/daspk/ddasid.f, liboctave/cruft/daspk/ddasik.f, liboctave/cruft/daspk/ddaspk.f, liboctave/cruft/daspk/ddstp.f, liboctave/cruft/daspk/ddwnrm.f, liboctave/cruft/daspk/dfnrmd.f, liboctave/cruft/daspk/dfnrmk.f, liboctave/cruft/daspk/dhels.f, liboctave/cruft/daspk/dheqr.f, liboctave/cruft/daspk/dinvwt.f, liboctave/cruft/daspk/dlinsd.f, liboctave/cruft/daspk/dlinsk.f, liboctave/cruft/daspk/dmatd.f, liboctave/cruft/daspk/dnedd.f, liboctave/cruft/daspk/dnedk.f, liboctave/cruft/daspk/dnsd.f, liboctave/cruft/daspk/dnsid.f, liboctave/cruft/daspk/dnsik.f, liboctave/cruft/daspk/dnsk.f, liboctave/cruft/daspk/dorth.f, liboctave/cruft/daspk/dslvd.f, liboctave/cruft/daspk/dslvk.f, liboctave/cruft/daspk/dspigm.f, liboctave/cruft/daspk/dyypnw.f, liboctave/cruft/dasrt/ddasrt.f, liboctave/cruft/dasrt/drchek.f, liboctave/cruft/dassl/ddaslv.f, liboctave/cruft/dassl/ddassl.f, liboctave/cruft/misc/blaswrap.c, liboctave/cruft/misc/module.mk, liboctave/cruft/odepack/cfode.f, liboctave/cruft/odepack/dlsode.f, liboctave/cruft/odepack/ewset.f, liboctave/cruft/odepack/intdy.f, liboctave/cruft/odepack/prepj.f, liboctave/cruft/odepack/sintdy.f, liboctave/cruft/odepack/slsode.f, liboctave/cruft/odepack/solsy.f, liboctave/cruft/odepack/ssolsy.f, liboctave/cruft/odepack/stode.f, liboctave/cruft/odepack/vnorm.f, liboctave/cruft/ranlib/Basegen.doc, liboctave/cruft/ranlib/README, liboctave/cruft/ranlib/genbet.f, liboctave/cruft/ranlib/genexp.f, liboctave/cruft/ranlib/gennch.f, liboctave/cruft/ranlib/gennf.f, liboctave/cruft/ranlib/gennor.f, liboctave/cruft/ranlib/getsd.f, liboctave/cruft/ranlib/initgn.f, liboctave/cruft/ranlib/phrtsd.f, liboctave/cruft/ranlib/randlib.fdoc, liboctave/cruft/ranlib/setsd.f, liboctave/cruft/ranlib/tstgmn.for, liboctave/cruft/ranlib/tstmid.for, liboctave/cruft/slatec-fn/atanh.f, liboctave/cruft/slatec-fn/datanh.f, liboctave/cruft/slatec-fn/xgmainc.f, liboctave/cruft/slatec-fn/xsgmainc.f, liboctave/numeric/module.mk, liboctave/operators/mk-ops.awk, liboctave/operators/mx-ops, liboctave/operators/sparse-mk-ops.awk, liboctave/operators/sparse-mx-ops, liboctave/operators/vx-ops, liboctave/util/module.mk, run-octave.in, scripts/@ftp/ftp.m, scripts/audio/wavread.m, scripts/deprecated/java_convert_matrix.m, scripts/deprecated/java_debug.m, scripts/deprecated/java_invoke.m, scripts/deprecated/java_new.m, scripts/deprecated/java_unsigned_conversion.m, scripts/deprecated/javafields.m, scripts/deprecated/javamethods.m, scripts/deprecated/shell_cmd.m, scripts/general/accumarray.m, scripts/general/display.m, scripts/general/fieldnames.m, scripts/general/interp1.m, scripts/general/interp2.m, scripts/general/interp3.m, scripts/general/isa.m, scripts/general/methods.m, scripts/general/sortrows.m, scripts/geometry/convhull.m, scripts/geometry/delaunay.m, scripts/geometry/delaunay3.m, scripts/geometry/delaunayn.m, scripts/geometry/griddata.m, scripts/geometry/griddatan.m, scripts/geometry/voronoi.m, scripts/geometry/voronoin.m, scripts/gui/guihandles.m, scripts/gui/inputdlg.m, scripts/gui/listdlg.m, scripts/gui/msgbox.m, scripts/gui/questdlg.m, scripts/gui/uigetfile.m, scripts/gui/waitbar.m, scripts/gui/warndlg.m, scripts/help/doc.m, scripts/help/help.m, scripts/help/type.m, scripts/image/bone.m, scripts/image/cmpermute.m, scripts/image/cmunique.m, scripts/image/colorcube.m, scripts/image/colormap.m, scripts/image/contrast.m, scripts/image/gray2ind.m, scripts/image/image.m, scripts/image/imshow.m, scripts/image/ind2gray.m, scripts/image/jet.m, scripts/image/rgb2ntsc.m, scripts/image/spinmap.m, scripts/io/importdata.m, scripts/io/strread.m, scripts/io/textread.m, scripts/io/textscan.m, scripts/java/java_get.m, scripts/java/java_set.m, scripts/java/javaaddpath.m, scripts/java/javaclasspath.m, scripts/java/javamem.m, scripts/linear-algebra/linsolve.m, scripts/linear-algebra/qzhess.m, scripts/miscellaneous/debug.m, scripts/miscellaneous/desktop.m, scripts/miscellaneous/dir.m, scripts/miscellaneous/dos.m, scripts/miscellaneous/edit.m, scripts/miscellaneous/fact.m, scripts/miscellaneous/getappdata.m, scripts/miscellaneous/inputname.m, scripts/miscellaneous/license.m, scripts/miscellaneous/ls_command.m, scripts/miscellaneous/run.m, scripts/miscellaneous/setfield.m, scripts/miscellaneous/unix.m, scripts/miscellaneous/ver.m, scripts/mk-pkg-add, scripts/mkdoc.pl, scripts/optimization/fminsearch.m, scripts/optimization/optimset.m, scripts/optimization/sqp.m, scripts/pkg/pkg.m, scripts/pkg/private/create_pkgadddel.m, scripts/pkg/private/fix_depends.m, scripts/pkg/private/install.m, scripts/plot/appearance/axis.m, scripts/plot/appearance/box.m, scripts/plot/appearance/clabel.m, scripts/plot/appearance/daspect.m, scripts/plot/appearance/datetick.m, scripts/plot/appearance/grid.m, scripts/plot/appearance/legend.m, scripts/plot/appearance/orient.m, scripts/plot/appearance/shading.m, scripts/plot/appearance/text.m, scripts/plot/appearance/title.m, scripts/plot/appearance/xlabel.m, scripts/plot/appearance/ylabel.m, scripts/plot/appearance/zlabel.m, scripts/plot/draw/area.m, scripts/plot/draw/bar.m, scripts/plot/draw/barh.m, scripts/plot/draw/colorbar.m, scripts/plot/draw/contour.m, scripts/plot/draw/contour3.m, scripts/plot/draw/contourf.m, scripts/plot/draw/ellipsoid.m, scripts/plot/draw/errorbar.m, scripts/plot/draw/ezcontour.m, scripts/plot/draw/ezcontourf.m, scripts/plot/draw/ezmesh.m, scripts/plot/draw/ezpolar.m, scripts/plot/draw/fill.m, scripts/plot/draw/fplot.m, scripts/plot/draw/hist.m, scripts/plot/draw/meshc.m, scripts/plot/draw/meshz.m, scripts/plot/draw/pareto.m, scripts/plot/draw/patch.m, scripts/plot/draw/peaks.m, scripts/plot/draw/pie.m, scripts/plot/draw/pie3.m, scripts/plot/draw/plot.m, scripts/plot/draw/plotyy.m, scripts/plot/draw/private/__bar__.m, scripts/plot/draw/private/__contour__.m, scripts/plot/draw/private/__errplot__.m, scripts/plot/draw/private/__ezplot__.m, scripts/plot/draw/private/__patch__.m, scripts/plot/draw/private/__stem__.m, scripts/plot/draw/rectangle.m, scripts/plot/draw/ribbon.m, scripts/plot/draw/rose.m, scripts/plot/draw/scatter.m, scripts/plot/draw/scatter3.m, scripts/plot/draw/semilogx.m, scripts/plot/draw/shrinkfaces.m, scripts/plot/draw/sombrero.m, scripts/plot/draw/sphere.m, scripts/plot/draw/stairs.m, scripts/plot/draw/stem.m, scripts/plot/draw/stemleaf.m, scripts/plot/draw/surf.m, scripts/plot/draw/surface.m, scripts/plot/draw/surfc.m, scripts/plot/draw/surfl.m, scripts/plot/draw/surfnorm.m, scripts/plot/draw/tetramesh.m, scripts/plot/draw/trimesh.m, scripts/plot/draw/triplot.m, scripts/plot/draw/trisurf.m, scripts/plot/util/__gnuplot_drawnow__.m, scripts/plot/util/__plt_get_axis_arg__.m, scripts/plot/util/axes.m, scripts/plot/util/clf.m, scripts/plot/util/copyobj.m, scripts/plot/util/figure.m, scripts/plot/util/gcbo.m, scripts/plot/util/graphics_toolkit.m, scripts/plot/util/hggroup.m, scripts/plot/util/meshgrid.m, scripts/plot/util/newplot.m, scripts/plot/util/print.m, scripts/plot/util/private/__add_default_menu__.m, scripts/plot/util/private/__fltk_print__.m, scripts/plot/util/private/__gnuplot_print__.m, scripts/plot/util/private/__print_parse_opts__.m, scripts/plot/util/refreshdata.m, scripts/plot/util/subplot.m, scripts/polynomial/conv.m, scripts/polynomial/poly.m, scripts/polynomial/polyeig.m, scripts/polynomial/polyfit.m, scripts/polynomial/polyval.m, scripts/polynomial/private/__splinefit__.m, scripts/polynomial/spline.m, scripts/prefs/prefdir.m, scripts/prefs/preferences.m, scripts/prefs/private/prefsfile.m, scripts/prefs/rmpref.m, scripts/signal/freqz.m, scripts/signal/module.mk, scripts/sparse/eigs.m, scripts/sparse/pcg.m, scripts/sparse/private/__sprand_impl__.m, scripts/sparse/sprand.m, scripts/sparse/sprandn.m, scripts/sparse/spy.m, scripts/sparse/svds.m, scripts/specfun/expint.m, scripts/specfun/factor.m, scripts/special-matrix/gallery.m, scripts/special-matrix/hankel.m, scripts/special-matrix/toeplitz.m, scripts/startup/inputrc, scripts/statistics/base/kurtosis.m, scripts/statistics/base/moment.m, scripts/statistics/base/qqplot.m, scripts/statistics/base/var.m, scripts/statistics/distributions/betarnd.m, scripts/statistics/distributions/binoinv.m, scripts/statistics/distributions/binopdf.m, scripts/statistics/distributions/binornd.m, scripts/statistics/distributions/cauchy_rnd.m, scripts/statistics/distributions/chi2rnd.m, scripts/statistics/distributions/discrete_pdf.m, scripts/statistics/distributions/discrete_rnd.m, scripts/statistics/distributions/empirical_rnd.m, scripts/statistics/distributions/exprnd.m, scripts/statistics/distributions/frnd.m, scripts/statistics/distributions/gamrnd.m, scripts/statistics/distributions/geornd.m, scripts/statistics/distributions/hygernd.m, scripts/statistics/distributions/kolmogorov_smirnov_cdf.m, scripts/statistics/distributions/laplace_cdf.m, scripts/statistics/distributions/laplace_pdf.m, scripts/statistics/distributions/logistic_cdf.m, scripts/statistics/distributions/logistic_pdf.m, scripts/statistics/distributions/lognrnd.m, scripts/statistics/distributions/nbincdf.m, scripts/statistics/distributions/nbininv.m, scripts/statistics/distributions/nbinpdf.m, scripts/statistics/distributions/nbinrnd.m, scripts/statistics/distributions/normrnd.m, scripts/statistics/distributions/poissinv.m, scripts/statistics/distributions/poissrnd.m, scripts/statistics/distributions/tinv.m, scripts/statistics/distributions/trnd.m, scripts/statistics/distributions/unidcdf.m, scripts/statistics/distributions/unidpdf.m, scripts/statistics/distributions/unidrnd.m, scripts/statistics/distributions/unifrnd.m, scripts/statistics/distributions/wblrnd.m, scripts/statistics/models/module.mk, scripts/statistics/tests/kruskal_wallis_test.m, scripts/strings/base2dec.m, scripts/strings/deblank.m, scripts/strings/dec2base.m, scripts/strings/dec2bin.m, scripts/strings/dec2hex.m, scripts/strings/mat2str.m, scripts/strings/ostrsplit.m, scripts/strings/regexptranslate.m, scripts/strings/str2num.m, scripts/strings/strcat.m, scripts/strings/strjoin.m, scripts/strings/strsplit.m, scripts/strings/strtok.m, scripts/strings/strtrim.m, scripts/strings/strtrunc.m, scripts/strings/substr.m, scripts/testfun/__run_test_suite__.m, scripts/testfun/speed.m, scripts/testfun/test.m, scripts/time/asctime.m, scripts/time/datenum.m, scripts/time/datevec.m, scripts/time/weekday.m, src/Makefile.am, test/Makefile.am, test/build-bc-overload-tests.sh, test/build-sparse-tests.sh, test/jit.tst, test/line-continue.tst: Strip trailing whitespace.
author John W. Eaton <jwe@octave.org>
date Tue, 20 Jan 2015 08:26:57 -0500
parents d63878346099
children 0e1f5a750d00
line wrap: on
line source

## Copyright (C) 2005-2013 Paul Kienzle
##
## This file is part of Octave.
##
## Octave is free software; you can redistribute it and/or modify it
## under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 3 of the License, or (at
## your option) any later version.
##
## Octave is distributed in the hope that it will be useful, but
## WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
## General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with Octave; see the file COPYING.  If not, see
## <http://www.gnu.org/licenses/>.

## -*- texinfo -*-
## @deftypefn  {Command} {} test @var{name}
## @deftypefnx {Command} {} test @var{name} quiet|normal|verbose
## @deftypefnx {Function File} {} test ("@var{name}", "quiet|normal|verbose", @var{fid})
## @deftypefnx {Function File} {} test ([], "explain", @var{fid})
## @deftypefnx {Function File} {@var{success} =} test (@dots{})
## @deftypefnx {Function File} {[@var{n}, @var{max}] =} test (@dots{})
## @deftypefnx {Function File} {[@var{code}, @var{idx}] =} test ("@var{name}", "grabdemo")
##
## Perform tests from the first file in the loadpath matching @var{name}.
## @code{test} can be called as a command or as a function.  Called with
## a single argument @var{name}, the tests are run interactively and stop
## after the first error is encountered.
##
## With a second argument the tests which are performed and the amount of
## output is selected.
##
## @table @asis
## @item @qcode{"quiet"}
##  Don't report all the tests as they happen, just the errors.
##
## @item @qcode{"normal"}
## Report all tests as they happen, but don't do tests which require
## user interaction.
##
## @item @qcode{"verbose"}
## Do tests which require user interaction.
## @end table
##
## The argument @var{fid} can be used to allow batch processing.  Errors
## can be written to the already open file defined by @var{fid}, and
## hopefully when Octave crashes this file will tell you what was happening
## when it did.  You can use @code{stdout} if you want to see the results as
## they happen.  You can also give a file name rather than an @var{fid}, in
## which case the contents of the file will be replaced with the log from
## the current test.
##
## Called with a single output argument @var{success}, @code{test} returns
## true if all of the tests were successful.  Called with two output arguments
## @var{n} and @var{max}, the number of successful tests and the total number
## of tests in the file @var{name} are returned.
##
## If the second argument is the string @qcode{"grabdemo"}, the contents of
## the demo blocks are extracted but not executed.  Code for all code blocks
## is concatenated and returned as @var{code} with @var{idx} being a vector
## of positions of the ends of the demo blocks.
##
## If the second argument is @qcode{"explain"}, then @var{name} is ignored
## and an explanation of the line markers used is written to the file
## @var{fid}.
## @seealso{assert, fail, error, demo, example}
## @end deftypefn

## FIXME: * Consider using keyword fail rather then error?  This allows us
## to make a functional form of error blocks, which means we
## can include them in test sections which means that we can use
## octave flow control for both kinds of tests.

function [__ret1, __ret2, __ret3, __ret4] = test (__name, __flag, __fid)
  ## Information from test will be introduced by "key".
  persistent __signal_fail =  "!!!!! ";
  persistent __signal_empty = "????? ";
  persistent __signal_block = "  ***** ";
  persistent __signal_file =  ">>>>> ";
  persistent __signal_skip = "----- ";

  __xfail = 0;
  __xskip = 0;

  if (nargin < 2 || isempty (__flag))
    __flag = "quiet";
  endif
  if (nargin < 3)
    __fid = [];
  endif
  if (nargin < 1 || nargin > 3
      || (! ischar (__name) && ! isempty (__name)) || ! ischar (__flag))
    print_usage ();
  endif
  if (isempty (__name) && (nargin != 3 || ! strcmp (__flag, "explain")))
    print_usage ();
  endif
  __batch = (! isempty (__fid));

  ## Decide if error messages should be collected.
  __close_fid = 0;
  if (__batch)
    if (ischar (__fid))
      __fid = fopen (__fid, "wt");
      if (__fid < 0)
        error ("test: could not open log file");
      endif
      __close_fid = 1;
    endif
    fprintf (__fid, "%sprocessing %s\n", __signal_file, __name);
    fflush (__fid);
  else
    __fid = stdout;
  endif

  if (strcmp (__flag, "normal"))
    __grabdemo = 0;
    __rundemo = 0;
    __verbose = __batch;
  elseif (strcmp (__flag, "quiet"))
    __grabdemo = 0;
    __rundemo = 0;
    __verbose = 0;
  elseif (strcmp (__flag, "verbose"))
    __grabdemo = 0;
    __rundemo = 1;
    __verbose = 1;
  elseif (strcmp (__flag, "grabdemo"))
    __grabdemo = 1;
    __rundemo = 0;
    __verbose = 0;
    __demo_code = "";
    __demo_idx = [];
  elseif (strcmp (__flag, "explain"))
    fprintf (__fid, "# %s new test file\n", __signal_file);
    fprintf (__fid, "# %s no tests in file\n", __signal_empty);
    fprintf (__fid, "# %s test had an unexpected result\n", __signal_fail);
    fprintf (__fid, "# %s code for the test\n", __signal_block);
    fprintf (__fid, "# Search for the unexpected results in the file\n");
    fprintf (__fid, "# then page back to find the file name which caused it.\n");
    fprintf (__fid, "# The result may be an unexpected failure (in which\n");
    fprintf (__fid, "# case an error will be reported) or an unexpected\n");
    fprintf (__fid, "# success (in which case no error will be reported).\n");
    fflush (__fid);
    if (__close_fid)
      fclose (__fid);
    endif
    return;
  else
    error ("test: unknown flag '%s'", __flag);
  endif

  ## Locate the file to test.
  __file = file_in_loadpath (__name, "all");
  if (isempty (__file))
    __file = file_in_loadpath ([__name ".m"], "all");
  endif
  if (isempty (__file))
    __file = file_in_loadpath ([__name ".cc"], "all");
  endif
  if (iscell (__file))
      ## If repeats, return first in path.
    if (isempty (__file))
      __file = "";
    else
      __file = __file{1};
    endif
  endif
  if (isempty (__file))
    if (__grabdemo)
      __ret1 = "";
      __ret2 = -1;
    else
      ftype = exist (__name);
      if (ftype == 3)
        fprintf (__fid, "%s%s source code with tests for dynamically linked function not found\n", __signal_empty, __name);
      elseif (ftype == 5)
        fprintf (__fid, "%s%s is a built-in function\n", __signal_empty, __name);
      elseif (any (strcmp (__operators__ (), __name)))
        fprintf (__fid, "%s%s is an operator\n", __signal_empty, __name);
      elseif (any (strcmp (__keywords__ (), __name)))
        fprintf (__fid, "%s%s is a keyword\n", __signal_empty, __name);
      else
        fprintf (__fid, "%s%s does not exist in path\n", __signal_empty, __name);
      endif
      fflush (__fid);
      if (nargout > 0)
        __ret1 = __ret2 = 0;
      endif
    endif
    if (__close_fid)
      fclose (__fid);
    endif
    return;
  endif

  ## Grab the test code from the file.
  __body = __extract_test_code (__file);

  if (isempty (__body))
    if (__grabdemo)
      __ret1 = "";
      __ret2 = [];
    else
      fprintf (__fid, "%s%s has no tests available\n", __signal_empty, __file);
      fflush (__fid);
      if (nargout > 0)
        __ret1 = __ret2 = 0;
      endif
    endif
    if (__close_fid)
      fclose (__fid);
    endif
    return;
  else
    ## Add a dummy comment block to the end for ease of indexing.
    if (__body (length (__body)) == "\n")
      __body = sprintf ("\n%s#", __body);
    else
      __body = sprintf ("\n%s\n#", __body);
    endif
  endif

  ## Chop it up into blocks for evaluation.
  __lineidx = find (__body == "\n");
  __blockidx = __lineidx(find (! isspace (__body(__lineidx+1))))+1;

  ## Ready to start tests ... if in batch mode, tell us what is happening.
  if (__verbose)
    disp ([__signal_file, __file]);
  endif

  ## Assume all tests will pass.
  __all_success = 1;

  ## Process each block separately, initially with no shared variables.
  __tests = __successes = 0;
  __shared = " ";
  __shared_r = " ";
  __clear = "";
  for __i = 1:length (__blockidx)-1

    ## Extract the block.
    __block = __body(__blockidx(__i):__blockidx(__i+1)-2);

    ## Let the user/logfile know what is happening.
    if (__verbose)
      fprintf (__fid, "%s%s\n", __signal_block, __block);
      fflush (__fid);
    endif

    ## Split __block into __type and __code.
    __idx = find (! isletter (__block));
    if (isempty (__idx))
      __type = __block;
      __code = "";
    else
      __type = __block(1:__idx(1)-1);
      __code = __block(__idx(1):length (__block));
    endif

    ## Assume the block will succeed.
    __success = 1;
    __msg = [];

### DEMO

    ## If in __grabdemo mode, then don't process any other block type.
    ## So that the other block types don't have to worry about
    ## this __grabdemo mode, the demo block processor grabs all block
    ## types and skips those which aren't demo blocks.

    __isdemo = strcmp (__type, "demo");
    if (__grabdemo || __isdemo)
      __istest = 0;

      if (__grabdemo && __isdemo)
        if (isempty (__demo_code))
          __demo_code = __code;
          __demo_idx = [1, length(__demo_code)+1];
        else
          __demo_code = [__demo_code, __code];
          __demo_idx = [__demo_idx, length(__demo_code)+1];
        endif

      elseif (__rundemo && __isdemo)
        try
          ## process the code in an environment without variables
          eval (sprintf ("function __test__ ()\n%s\nendfunction", __code));
          __test__;
          input ("Press <enter> to continue: ", "s");
        catch
          __success = 0;
          __msg = sprintf ("%sdemo failed\n%s",  __signal_fail, lasterr ());
        end_try_catch
        clear __test__;

      endif
      ## Code already processed.
      __code = "";

### SHARED

    elseif (strcmp (__type, "shared"))
      __istest = 0;

      ## Separate initialization code from variables.
      __idx = find (__code == "\n");
      if (isempty (__idx))
        __vars = __code;
        __code = "";
      else
        __vars = __code (1:__idx(1)-1);
        __code = __code (__idx(1):length (__code));
      endif

      ## Strip comments off the variables.
      __idx = find (__vars == "%" | __vars == "#");
      if (! isempty (__idx))
        __vars = __vars(1:__idx(1)-1);
      endif

      ## Assign default values to variables.
      try
        __vars = deblank (__vars);
        if (! isempty (__vars))
          eval ([strrep(__vars, ",", "=[];"), "=[];"]);
          __shared = __vars;
          __shared_r = ["[ ", __vars, "] = "];
        else
          __shared = " ";
          __shared_r = " ";
        endif
      catch
        ## Couldn't declare, so don't initialize.
        __code = "";
        __success = 0;
        __msg = sprintf ("%sshared variable initialization failed\n",
                         __signal_fail);
      end_try_catch

      ## Initialization code will be evaluated below.

### FUNCTION

    elseif (strcmp (__type, "function"))
      __istest = 0;
      persistent __fn = 0;
      __name_position = function_name (__block);
      if (isempty (__name_position))
        __success = 0;
        __msg = sprintf ("%stest failed: missing function name\n",
                         __signal_fail);
      else
        __name = __block(__name_position(1):__name_position(2));
        __code = __block;
        try
          eval (__code);  # Define the function
          __clear = sprintf ("%sclear %s;\n", __clear, __name);
        catch
          __success = 0;
          __msg = sprintf ("%stest failed: syntax error\n%s",
                           __signal_fail, lasterr ());
        end_try_catch
      endif
      __code = "";

### ENDFUNCTION

    elseif (strcmp (__type, "endfunction"))
      ## endfunction simply declares the end of a previous function block.
      ## There is no processing to be done here, just skip to next block.
      __istest = 0;
      __code = "";

### ASSERT/FAIL

    elseif (strcmp (__type, "assert") || strcmp (__type, "fail"))
      __istest = 1;
      ## Put the keyword back on the code.
      __code = __block;
      ## The code will be evaluated below as a test block.

### ERROR/WARNING

    elseif (strcmp (__type, "error") || strcmp (__type, "warning"))
      __istest = 1;
      __warning = strcmp (__type, "warning");
      [__pattern, __id, __code] = getpattern (__code);
      if (__id)
        __patstr = ["id=",__id];
      else
        if (! strcmp (__pattern, '.'))
          __patstr = ["<",__pattern,">"];
        else
          __patstr = ifelse (__warning, "a warning", "an error");
        endif
      endif
      try
        eval (sprintf ("function __test__(%s)\n%s\nendfunction",
                       __shared, __code));
      catch
        __success = 0;
        __msg = sprintf ("%stest failed: syntax error\n%s",
                         __signal_fail, lasterr ());
      end_try_catch

      if (__success)
        __success = 0;
        __warnstate = warning ("query", "quiet");
        warning ("on", "quiet");
        ## Clear error and warning strings before starting
        lasterr ("");
        lastwarn ("");
        try
          ## FIXME: lastwarn () must be called once from *WITHIN* the try block
          ##        or subsequent warning/lastwarn statements may fail.
          ##        Likely this is something to do with the specialness of
          ##        the try block which is disabling normal errors.
          lastwarn ();
          eval (sprintf ("__test__(%s);", __shared));
          if (! __warning)
            __msg = sprintf ("%serror failed.\nExpected %s but got no error\n",
                             __signal_fail, __patstr);
          else
            if (! isempty (__id))
              [~, __err] = lastwarn ();
              __mismatch = ! strcmp (__err, __id);
            else
              __err = trimerr (lastwarn (), "warning");
              __mismatch = isempty (regexp (__err, __pattern, "once"));
            endif
            warning (__warnstate.state, "quiet");
            if (isempty (__err))
              __msg = sprintf (["%swarning failed.\n" ...
                                "Expected %s but got no warning\n"],
                               __signal_fail, __patstr);
            elseif (__mismatch)
              __msg = sprintf ("%swarning failed.\nExpected %s but got <%s>\n",
                               __signal_fail, __patstr, __err);
            else
              __success = 1;
            endif
          endif

        catch
          if (! isempty (__id))
            [~, __err] = lasterr ();
            __mismatch = ! strcmp (__err, __id);
          else
            __err = trimerr (lasterr (), "error");
            __mismatch = isempty (regexp (__err, __pattern, "once"));
          endif
          warning (__warnstate.state, "quiet");
          if (__warning)
            __msg = sprintf (["%swarning failed.\n" ...
                              "Expected warning %s but got error <%s>\n"],
                             __signal_fail, __patstr, __err);
          elseif (__mismatch)
            __msg = sprintf ("%serror failed.\nExpected %s but got <%s>\n",
                             __signal_fail, __patstr, __err);
          else
            __success = 1;
          endif
        end_try_catch
        clear __test__;
      endif
      ## Code already processed.
      __code = "";

### TESTIF

    elseif (strcmp (__type, "testif"))
      __e = regexp (__code, '.$', 'lineanchors', 'once');
      ## Strip comment any comment from testif line before looking for features
      __feat_line = strtok (__code(1:__e), '#%');
      __feat = regexp (__feat_line, '\w+', 'match');
      __feat = strrep (__feat, "HAVE_", "");
      __have_feat = __have_feature__ (__feat);
      if (__have_feat)
        __istest = 1;
        __code = __code(__e + 1 : end);
      else
        __xskip++;
        __istest = 0;
        __code = ""; # Skip the code.
        __msg = sprintf ("%sskipped test\n", __signal_skip);
      endif

### TEST

    elseif (strcmp (__type, "test") || strcmp (__type, "xtest"))
      __istest = 1;
      ## Code will be evaluated below.

### Comment block.

    elseif (strcmp (__block(1:1), "#"))
      __istest = 0;
      __code = ""; # skip the code

### Unknown block.

    else
      __istest = 1;
      __success = 0;
      __msg = sprintf ("%sunknown test type!\n", __signal_fail);
      __code = ""; # skip the code
    endif

    ## evaluate code for test, shared, and assert.
    if (! isempty(__code))
      try
        ## FIXME: need to check for embedded test functions, which cause
        ## segfaults, until issues with subfunctions in functions are resolved.
        embed_func = regexp (__code, '^\s*function ', 'once', 'lineanchors');
        if (isempty (embed_func))
          eval (sprintf ("function %s__test__(%s)\n%s\nendfunction",
                         __shared_r,__shared, __code));
          eval (sprintf ("%s__test__(%s);", __shared_r, __shared));
        else
          error (["Functions embedded in %!test blocks are not allowed.\n", ...
                  "Use the %!function/%!endfunction syntax instead to define shared functions for testing.\n"]);
        endif
      catch
        if (strcmp (__type, "xtest"))
           __msg = sprintf ("%sknown failure\n%s", __signal_fail, lasterr ());
           __xfail++;
        else
           __msg = sprintf ("%stest failed\n%s", __signal_fail, lasterr ());
           __success = 0;
        endif
        if (isempty (lasterr ()))
          error ("empty error text, probably Ctrl-C --- aborting");
        endif
      end_try_catch
      clear __test__;
    endif

    ## All done.  Remember if we were successful and print any messages.
    if (! isempty (__msg))
      ## Make sure the user knows what caused the error.
      if (! __verbose)
        fprintf (__fid, "%s%s\n", __signal_block, __block);
        fflush (__fid);
      endif
      fputs (__fid, __msg);
      fputs (__fid, "\n");
      fflush (__fid);
      ## Show the variable context.
      if (! strcmp (__type, "error") && ! strcmp (__type, "testif")
          && ! all (__shared == " "))
        fputs (__fid, "shared variables ");
        eval (sprintf ("fdisp(__fid,bundle(%s));", __shared));
        fflush (__fid);
      endif
    endif
    if (__success == 0)
      __all_success = 0;
      ## Stop after one error if not in batch mode.
      if (! __batch)
        if (nargout > 0)
          __ret1 = __ret2 = 0;
        endif
        if (__close_fid)
          fclose (__fid);
        endif
        return;
      endif
    endif
    __tests += __istest;
    __successes += __success * __istest;
  endfor
  ## Clear any test functions created
  eval (__clear, "");

  if (nargout == 0)
    if (__tests || __xfail || __xskip)
      if (__xfail)
        printf ("PASSES %d out of %d test%s (%d expected failure%s)\n",
                __successes, __tests, ifelse (__tests > 1, "s", ""),
                __xfail, ifelse (__xfail > 1, "s", ""));
      else
        printf ("PASSES %d out of %d test%s\n", __successes, __tests,
               ifelse (__tests > 1, "s", ""));
      endif
      if (__xskip)
        printf ("Skipped %d test%s due to missing features\n", __xskip,
                ifelse (__xskip > 1, "s", ""));
      endif
    else
      printf ("%s%s has no tests available\n", __signal_empty, __file);
    endif
  elseif (__grabdemo)
    __ret1 = __demo_code;
    __ret2 = __demo_idx;
  elseif (nargout == 1)
    __ret1 = __all_success;
  else
    __ret1 = __successes;
    __ret2 = __tests;
    __ret3 = __xfail;
    __ret4 = __xskip;
  endif
endfunction

## Create structure with fieldnames the name of the input variables.
function s = varstruct (varargin)
  for i = 1:nargin
    s.(deblank (argn(i,:))) = varargin{i};
  endfor
endfunction

## Find [start,end] of fn in 'function [a,b] = fn'.
function pos = function_name (def)
  pos = [];

  ## Find the end of the name.
  right = find (def == "(", 1);
  if (isempty (right))
    return;
  endif
  right = find (def(1:right-1) != " ", 1, "last");

  ## Find the beginning of the name.
  left = max ([find(def(1:right)==" ", 1, "last"), ...
               find(def(1:right)=="=", 1, "last")]);
  if (isempty (left))
    return;
  endif
  left++;

  ## Return the end points of the name.
  pos = [left, right];
endfunction

## Strip <pattern> from '<pattern> code'.
## Also handles 'id=ID code'
function [pattern, id, rest] = getpattern (str)
  pattern = ".";
  id = [];
  rest = str;
  str = trimleft (str);
  if (! isempty (str) && str(1) == "<")
    close = index (str, ">");
    if (close)
      pattern = str(2:close-1);
      rest = str(close+1:end);
    endif
  elseif (strncmp (str, "id=", 3))
    [id, rest] = strtok (str(4:end));
  endif
endfunction

## Strip '.*prefix:' from '.*prefix: msg\n' and strip trailing blanks.
function msg = trimerr (msg, prefix)
  idx = index (msg, [prefix ":"]);
  if (idx > 0)
    msg(1:idx+length(prefix)) = [];
  endif
  msg = strtrim (msg);
endfunction

## Strip leading blanks from string.
function str = trimleft (str)
  idx = find (! isspace (str), 1);
  str = str(idx:end);
endfunction

## Make a structure out of the named variables
## (based on Etienne Grossmann's tar function).
function s = bundle (varargin)
  for i = 1:nargin
    s.(deblank (argn(i,:))) = varargin{i};
  endfor
endfunction

function body = __extract_test_code (nm)
  fid = fopen (nm, "rt");
  body = [];
  if (fid >= 0)
    while (! feof (fid))
      ln = fgetl (fid);
      if (length (ln) >= 2 && strcmp (ln(1:2), "%!"))
        body = [body, "\n"];
        if (length (ln) > 2)
          body = [body, ln(3:end)];
        endif
      endif
    endwhile
    fclose (fid);
  endif
endfunction


### example from toeplitz
%!shared msg1,msg2
%! msg1="C must be a vector";
%! msg2="C and R must be vectors";
%!fail ('toeplitz ([])', msg1);
%!fail ('toeplitz ([1,2;3,4])', msg1);
%!fail ('toeplitz ([1,2],[])', msg2);
%!fail ('toeplitz ([1,2],[1,2;3,4])', msg2);
%!fail ('toeplitz ([1,2;3,4],[1,2])', msg2);
% !fail ('toeplitz','usage: toeplitz'); # usage doesn't generate an error
% !fail ('toeplitz (1, 2, 3)', 'usage: toeplitz');
%!test  assert (toeplitz ([1,2,3], [1,4]), [1,4; 2,1; 3,2]);
%!demo  toeplitz ([1,2,3,4],[1,5,6])

### example from kron
%!#error kron  # FIXME suppress these until we can handle output
%!#error kron(1,2,3)
%!test assert (isempty (kron ([], rand (3, 4))))
%!test assert (isempty (kron (rand (3, 4), [])))
%!test assert (isempty (kron ([], [])))
%!shared A, B
%!test
%! A = [1, 2, 3; 4, 5, 6];
%! B = [1, -1; 2, -2];
%!assert (size (kron (zeros (3, 0), A)), [ 3*rows(A), 0 ])
%!assert (size (kron (zeros (0, 3), A)), [ 0, 3*columns(A) ])
%!assert (size (kron (A, zeros (3, 0))), [ 3*rows(A), 0 ])
%!assert (size (kron (A, zeros (0, 3))), [ 0, 3*columns(A) ])
%!assert (kron (pi, e), pi*e)
%!assert (kron (pi, A), pi*A)
%!assert (kron (A, e), e*A)
%!assert (kron ([1, 2, 3], A), [ A, 2*A, 3*A ])
%!assert (kron ([1; 2; 3], A), [ A; 2*A; 3*A ])
%!assert (kron ([1, 2; 3, 4], A), [ A, 2*A; 3*A, 4*A ])
%!test
%! 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];
%! assert (kron (A, B), res)

### an extended demo from specgram
%!#demo
%! ## Speech spectrogram
%! [x, Fs] = auload (file_in_loadpath ("sample.wav")); # audio file
%! step = fix (5*Fs/1000);     # one spectral slice every 5 ms
%! window = fix (40*Fs/1000);  # 40 ms data window
%! fftn = 2^nextpow2 (window); # next highest power of 2
%! [S, f, t] = specgram (x, fftn, Fs, window, window-step);
%! S = abs (S (2:fftn*4000/Fs,:)); # magnitude in range 0<f<=4000 Hz.
%! S = S/max(max(S));          # normalize magnitude so that max is 0 dB.
%! S = max (S, 10^(-40/10));   # clip below -40 dB.
%! S = min (S, 10^(-3/10));    # clip above -3 dB.
%! imagesc (flipud (20*log10 (S)), 1);
%! % you should now see a spectrogram in the image window


## now test 'test' itself

## usage and error testing
% !fail ('test','usage.*test')           # no args, generates usage()
% !fail ('test (1,2,3,4)','usage.*test') # too many args, generates usage()
%!fail ('test ("test", "bogus")','unknown flag')  # incorrect args
%!fail ('garbage','garbage.*undefined')  # usage on nonexistent function should be

%!error test                     # no args, generates usage()
%!error test (1,2,3,4)           # too many args, generates usage()
%!error <unknown flag> test ("test", 'bogus'); # incorrect args, generates error()
%!error <garbage' undefined> garbage           # usage on nonexistent function should be

%!error test ("test", 'bogus');  # test without pattern

%!test
%! lastwarn();            # clear last warning just in case

%!warning <warning message> warning ('warning message');

## test of shared variables
%!shared a                # create a shared variable
%!test   a=3;             # assign to a shared variable
%!test   assert (a,3)     # variable should equal 3
%!shared b,c              # replace shared variables
%!test assert (!exist ("a", "var"));  # a no longer exists
%!test assert (isempty (b));   # variables start off empty
%!shared a,b,c            # recreate a shared variable
%!test assert (isempty (a));   # value is empty even if it had a previous value
%!test a=1; b=2; c=3;   # give values to all variables
%!test assert ([a,b,c],[1,2,3]); # test all of them together
%!test c=6;             # update a value
%!test assert ([a, b, c],[1, 2, 6]); # show that the update sticks
%!shared                     # clear all shared variables
%!test assert (!exist ("a", "var")) # show that they are cleared
%!shared a,b,c               # support for initializer shorthand
%! a=1; b=2; c=4;

%!function x = __test_a (y)
%! x = 2*y;
%!endfunction
%!assert (__test_a (2),4);       # Test a test function

%!function __test_a (y)
%! x = 2*y;
%!endfunction
%!test
%! __test_a (2);                # Test a test function with no return value

%!function [x,z] = __test_a (y)
%! x = 2*y;
%! z = 3*y;
%!endfunction
%!test                   # Test a test function with multiple returns
%! [x,z] = __test_a (3);
%! assert (x,6);
%! assert (z,9);

## test of assert block
%!assert (isempty ([]))      # support for test assert shorthand

## demo blocks
%!demo                   # multiline demo block
%! t = [0:0.01:2*pi]; x = sin (t);
%! plot (t,x);
%! % you should now see a sine wave in your figure window
%!demo a=3               # single line demo blocks work too

## this is a comment block. it can contain anything.
%!##
%! it is the "#" as the block type that makes it a comment
%! and it stays as a comment even through continuation lines
%! which means that it works well with commenting out whole tests

% !# failure tests.  All the following should fail. These tests should
% !# be disabled unless you are developing test() since users don't
% !# like to be presented with expected failures.  I use % ! to disable.
% !test   error("---------Failure tests.  Use test('test','verbose',1)");
% !test   assert([a,b,c],[1,3,6]);   # variables have wrong values
% !bogus                     # unknown block type
% !error  toeplitz([1,2,3]); # correct usage
% !test   syntax errors)     # syntax errors fail properly
% !shared garbage in         # variables must be comma separated
% !error  syntax++error      # error test fails on syntax errors
% !error  "succeeds.";       # error test fails if code succeeds
% !error <wrong pattern> error("message")  # error pattern must match
% !demo   with syntax error  # syntax errors in demo fail properly
% !shared a,b,c
% !demo                      # shared variables not available in demo
% ! assert(exist("a", "var"))
% !error
% ! test('/etc/passwd');
% ! test("nonexistent file");
% ! ## These don't signal an error, so the test for an error fails. Note
% ! ## that the call doesn't reference the current fid (it is unavailable),
% ! ## so of course the informational message is not printed in the log.