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 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():
    if[matlab, '-batch', 'exit(isempty(pyversion))'], timeout=60).returncode:
        pytest.skip('Python not setup in Matlab')

    subprocess.check_call([MATLAB, '-batch', 'test_api'],
                          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 file, and is named like test_api.m.


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