classdef meq_fixture < matlab.unittest.fixtures.Fixture
  % common fixtures for all meq tests (for use as shared fixture)
  %
  % [+MEQ MatlabEQuilibrium Toolbox+] Swiss Plasma Center EPFL Lausanne 2022. All rights reserved.
  
  methods
    function setup(fixture)
      % Save old path
      fixture.addTeardown(@path,path);
      
      % Paths to be tested
      meqpath = fullfile(fileparts(mfilename('fullpath')),'..');
      genlibpath = fullfile(meqpath,'genlib');
      hasgenlib = exist(fullfile(genlibpath,['greenemmex.',mexext]),'file');
      
      %% Remove possible spurious paths
      % remove possible other meq or genlib paths to avoid conflicts
      allmeq = which('liuqe','-all');
      allgenlib = which('greenem','-all');

      if ~isempty(allmeq)
        for ii=1:numel(allmeq)
          allmeq{ii} = fileparts(allmeq{ii});
        end
      end
      
      if ~isempty(allgenlib)
        for ii=1:numel(allgenlib)
          allgenlib{ii} = fileparts(allgenlib{ii});
        end
      elseif ~hasgenlib
        error('meq_fixture: genlib submodule is absent and it is not available in the MATLAB path');
      end

      if hasgenlib, allrm = [allmeq;allgenlib];
      else,         allrm = allmeq;
      end
      if ~isempty(allrm)
        w = warning('off','MATLAB:rmpath:DirNotFound');
        rmpath(allrm{:});
        warning(w);
        rmstr = sprintf('Removed: [%s]',strjoin(allrm,','));
      else
        rmstr = 'Removed: none';
      end
      
      %% add main meq path for this test
      if hasgenlib, alladd = {meqpath,genlibpath};
      else,         alladd = {meqpath};
      end
      addpath(alladd{:});
      addstr = sprintf('Added [%s] to path',strjoin(alladd,','));
      
      %%
      if ~hasgenlib, genlibstr=sprintf('\nUsing genlib at %s',allgenlib{1});
      else,          genlibstr='';
      end
      fixture.SetupDescription = [sprintf('\n%s\n%s',rmstr,addstr),genlibstr];
      fixture.TeardownDescription = 'Restored original paths';
    end
    
  end
end
