Running Matlab and GNU Octave via Pytest

A software package may have Matlab and Python functions. Plain Matlab code can be included via Pytest for Matlab and GNU Octave. To test the Matlab functions from Pytest, create a test_matlab.py file like:

from pathlib import Path
import subprocess
import pytest
import shutil

R = Path(__file__).parent

OCTAVE = shutil.which('octave-cli')
MATLAB = shutil.which('matlab')


@pytest.mark.skipif(not MATLAB, reason="Matlab not available")
def test_matlab_api():

    subprocess.check_call([MATLAB, '-batch', 'assertSuccess(runtests)'],
                          cwd=R, timeout=60)


@pytest.mark.skipif(not OCTAVE, reason='octave not found')
def test_octave_api():

    subprocess.check_call([OCTAVE, 'test_api.m'],
                          cwd=R, timeout=60)

This assumes the Matlab test script resides in the same directory as the test_matlab.py file, and is named like test_api.m.

NOTE: Be sure that Matlab “runtests()” actually picks up the desired tests. We do not want the Matlab output to say

Totals:
   0 Passed, 0 Failed, 0 Incomplete.
   0 seconds testing time.

Notes

Generally using __file__ is not robust for packages but we might relax that restriction for test files where a clear error will result.