0

In my python programming, I use the "If name == main:" test to include test cases in my individual modules. Here is a typical set up:

def addition (a, b):
    return a+b

if __name__ == '__main__':

    x = 4
    y = 6

    print addition(x,y)

Where 'addition' is my function. If function is called from another module, passing some inputs a and b, addition will return the sum. Additionally, I can run this script directly (suppose it is saved as addition.py), in which case the if clause will return True and proceed to the print statement, which is a trivial test case.

For more detailed explanation of the "if name == main" construction, see this SO post.

My question:

Is there a way to mimic this structure in Octave programming language? I would like to know if there is a similar way to write test cases into my Octave scripts, such that the test case will run if I run the script directly but will not run if the script is called by another program.

Community
  • 1
  • 1

1 Answers1

2

Octave has test and demos blocks which are documented on its manual. However, I'd still point you to its source for examples (since Octave uses them internally), rather than the manual. Look at the bottom of the function files for strjoin and rot90 for their tests.

Your specific example could become (I used 2 different types of test for sake of example):

function c = addition (a, b)
  c = a+b;
endfunction

%!assert (addition (4, 6), 10)

%!test
%! a = 4;
%! b = -4;
%! c = addition (a, b);
%! assert (c, 0)

This could be easily tested from the Octave prompt with test addition.

carandraug
  • 12,938
  • 1
  • 26
  • 38