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():
    if subprocess.run([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)


if __name__ == '__main__':
    pytest.main(['-r', 'a', '-v', __file__])

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